repo_url stringclasses 14
values | instruction stringlengths 17 1.08k | base_commit stringlengths 7 7 | requirements_txt stringclasses 14
values | testbed_environment stringclasses 2
values | solution_commit stringlengths 7 9 | solution_patch stringlengths 238 19.4k | modified_files listlengths 0 6 | id stringlengths 3 5 | language stringclasses 2
values | test_script stringlengths 553 11.4k |
|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/teamqurrent/httpx | Add None as default value for file parameter inside `httpx/_auth.py` class constructor | 4b5a92e | sniffio
rfc3986
httpcore>=0.18.0,<0.19.0
certifi
idna | python3.9 | c1cc6b2 | diff --git a/httpx/_auth.py b/httpx/_auth.py
--- a/httpx/_auth.py
+++ b/httpx/_auth.py
@@ -147,7 +147,7 @@ class NetRCAuth(Auth):
Use a 'netrc' file to lookup basic auth credentials based on the url host.
"""
- def __init__(self, file: typing.Optional[str]):
+ def __init__(self, file: typing.Optional[... | [
{
"content": "import hashlib\nimport netrc\nimport os\nimport re\nimport time\nimport typing\nfrom base64 import b64encode\nfrom urllib.request import parse_http_list\n\nfrom ._exceptions import ProtocolError\nfrom ._models import Request, Response\nfrom ._utils import to_bytes, to_str, unquote\n\nif typing.TYP... | 0_0 | python | import sys
import unittest
import inspect
class TestNetRCAuthFileParam(unittest.TestCase):
def test_netrcauth_file_param_default(self):
from httpx._auth import NetRCAuth
if hasattr(NetRCAuth, "__init__"):
init_method = getattr(NetRCAuth, "__init__")
method_signature = ins... |
https://github.com/teamqurrent/httpx | Allow tuple or list for multipart values inside `httpx/_multipart.py` in `_iter_fields` method | ccd98b1 | sniffio
rfc3986
httpcore>=0.18.0,<0.19.0
certifi
idna | python3.9 | 965b8ad | diff --git a/httpx/_multipart.py b/httpx/_multipart.py
--- a/httpx/_multipart.py
+++ b/httpx/_multipart.py
@@ -205,7 +205,7 @@ class MultipartStream(SyncByteStream, AsyncByteStream):
self, data: dict, files: RequestFiles
) -> typing.Iterator[typing.Union[FileField, DataField]]:
for name, value in... | [
{
"content": "import binascii\nimport io\nimport os\nimport typing\nfrom pathlib import Path\n\nfrom ._types import (\n AsyncByteStream,\n FileContent,\n FileTypes,\n RequestFiles,\n SyncByteStream,\n)\nfrom ._utils import (\n format_form_param,\n guess_content_type,\n peek_filelike_leng... | 0_1 | python | import sys
import unittest
import inspect
class TestMultipartStreamIterFields(unittest.TestCase):
def test_iter_fields_code(self):
from httpx._multipart import MultipartStream
source_lines = inspect.getsourcelines(MultipartStream._iter_fields)
found_isinstance_tuple = any("isinstance" in... |
https://github.com/teamqurrent/httpx | The `primitive_value_to_str` function inside `httpx/_utils.py` returns 'true' or 'false' or '' when the value is boolean or None. It returns str(value) otherwise. Modify primitive_value_to_str function to return str(value) if value is of type str, float or int. Otherwise raise TypeError with the error message: 'Expecte... | 10a3b68 | sniffio
rfc3986
httpcore>=0.18.0,<0.19.0
certifi
idna | python3.9 | 4cbf13e | diff --git a/httpx/_utils.py b/httpx/_utils.py
--- a/httpx/_utils.py
+++ b/httpx/_utils.py
@@ -67,7 +67,11 @@ def primitive_value_to_str(value: "PrimitiveData") -> str:
return "false"
elif value is None:
return ""
- return str(value)
+ elif isinstance(value, (str, float, int)):
+ ret... | [
{
"content": "import codecs\nimport email.message\nimport logging\nimport mimetypes\nimport netrc\nimport os\nimport re\nimport sys\nimport time\nimport typing\nfrom pathlib import Path\nfrom urllib.request import getproxies\n\nimport sniffio\n\nfrom ._types import PrimitiveData\n\nif typing.TYPE_CHECKING: # p... | 0_2 | python | import sys
import unittest
class TestHttpxQueryParams(unittest.TestCase):
def test_query_params_with_bytes(self):
import httpx
try:
httpx.QueryParams({"a": b"bytes"})
self.fail("TypeError not raised")
except TypeError as e:
expected_message = "Expected... |
https://github.com/teamqurrent/httpx | Delete `setup.py` | e5bc1ea | python3.9 | 10a3b68 | diff --git a/setup.py b/setup.py
deleted file mode 100644
--- a/setup.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import sys
-
-from setuptools import setup
-
-sys.stderr.write(
- """
-===============================
-Unsupported installation method
-===============================
-httpx no longer supports installation with... | [
{
"content": "import sys\n\nfrom setuptools import setup\n\nsys.stderr.write(\n \"\"\"\n===============================\nUnsupported installation method\n===============================\nhttpx no longer supports installation with `python setup.py install`.\nPlease use `python -m pip install .` instead.\n\"\"... | 0_3 | python | import os
import sys
import unittest
class TestSetupPyExists(unittest.TestCase):
def test_setup_py_existence(self):
# Get the current directory path
directory_path = os.getcwd()
# List all files in the directory
files = os.listdir(directory_path)
# Check if setup.py exists... | |
https://github.com/teamqurrent/httpx | Modify the encoding setter method of the `Headers` class to throw a ValueError if the class instance already as a `_text` attribute | e4241c6 | sniffio
rfc3986
httpcore>=0.18.0,<0.19.0
certifi
idna | python3.9 | 59df819 | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
+## Unreleased
+
+### Fixed
+
+* Raise `ValueError` on `Response.enco... | [
{
"content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).\n\n## 0.25.0 (11th Sep, 2023)\n\n### Removed\n\n* Drop support for Python 3.7. (#2813)\n\n### Added\n\n* Support HTTPS proxies. (#... | 0_4 | python | import sys
import unittest
import inspect
class TestResponseForceEncoding(unittest.TestCase):
def test_response_force_encoding_after_text_accessed(self):
import httpx
response = httpx.Response(
200,
content=b"Hello, world!",
)
self.assertEqual(response.stat... |
https://github.com/teamqurrent/discord.py | Your task is to add support for the Latin American Spanish locale to the discord.py library. This involves updating the `Locale` enumeration in the `enums.py` file to include the new locale. The locale code is es-419 | 08ef42f | discord | python3.9 | 2a59e028 | diff --git a/discord/enums.py b/discord/enums.py
--- a/discord/enums.py
+++ b/discord/enums.py
@@ -690,6 +690,7 @@ class Locale(Enum):
italian = 'it'
japanese = 'ja'
korean = 'ko'
+ latin_american_spanish = 'es-419'
lithuanian = 'lt'
norwegian = 'no'
polish = 'pl'
diff --git a/docs/api.... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_0 | python | import unittest
import sys
class TestLocaleAddition(unittest.TestCase):
def test_latin_american_spanish_locale(self):
from discord.enums import Locale
# Check if the Latin American Spanish locale is present in the Locale enumeration
self.assertTrue(hasattr(Locale, 'latin_american_spanish'... |
https://github.com/teamqurrent/discord.py | Your task is to introduce new message types related to guild incidents in the discord.py library. Specifically, add the message types guild_incident_alert_mode_enabled, guild_incident_alert_mode_disabled, guild_incident_report_raid, and guild_incident_report_false_alarm with respective values 36, 37, 38, and 39. These ... | 9db0dad | discord | python3.9 | 08ef42fe | diff --git a/discord/enums.py b/discord/enums.py
--- a/discord/enums.py
+++ b/discord/enums.py
@@ -247,6 +247,10 @@ class MessageType(Enum):
stage_raise_hand = 30
stage_topic = 31
guild_application_premium_subscription = 32
+ guild_incident_alert_mode_enabled = 36
+ guild_incident_alert_mode_disabl... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_1 | python | import unittest
import sys
class TestNewIncidentMessageTypes(unittest.TestCase):
def setUp(self):
from unittest.mock import Mock
# Mock data for testing
self.mock_state = Mock()
self.mock_channel = Mock()
self.mock_data = {'type': 0, 'content': '', 'author': {'id': 123, '... |
https://github.com/teamqurrent/discord.py | in the `discord/state.py` file, locate the `parse_entitlement_delete` method within the `ConnectionState` class. Change the event name in the dispatch call from 'entitlement_update' to 'entitlement_delete'. This modification ensures that the correct event is dispatched when the `parse_entitlement_delete` method is invo... | 99618c8 | discord | python3.9 | 7d159920 | diff --git a/discord/state.py b/discord/state.py
--- a/discord/state.py
+++ b/discord/state.py
@@ -1595,7 +1595,7 @@ class ConnectionState(Generic[ClientT]):
def parse_entitlement_delete(self, data: gw.EntitlementDeleteEvent) -> None:
entitlement = Entitlement(data=data, state=self)
- self.dispat... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_10 | python | import unittest
import sys
import inspect
class TestEntitlementDeleteEventDispatch(unittest.TestCase):
def test_entitlement_delete_event_dispatch(self):
from discord.state import ConnectionState
# Inspect the ConnectionState class for the parse_entitlement_delete method
method = getat... |
https://github.com/teamqurrent/discord.py | Enhance the `HTTPClient` class in `http.py` to allow editing various application details via Discord's API. Implement the `edit_application_info` method to send a PATCH request to the /applications/@me endpoint. This method should accept reason and payload, filter the payload for specific valid keys like 'custom_instal... | 9810cb9 | discord | python3.9 | 56c67d39 | diff --git a/discord/appinfo.py b/discord/appinfo.py
--- a/discord/appinfo.py
+++ b/discord/appinfo.py
@@ -30,8 +30,11 @@ from . import utils
from .asset import Asset
from .flags import ApplicationFlags
from .permissions import Permissions
+from .utils import MISSING
if TYPE_CHECKING:
+ from typing import Dict... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_3 | python | import unittest
import asyncio
import sys
class TestEditApplicationInfo(unittest.TestCase):
def setUp(self):
from discord.http import HTTPClient
from unittest.mock import MagicMock
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.http_client = HT... |
https://github.com/teamqurrent/discord.py | Enhance the `AutoModRuleAction` class in `automod.py` by modifying its `__init__` method to handle different action types more effectively. Specifically, implement conditional logic to set and validate attributes based on the action type: ensure channel_id is assigned for send_alert_message actions, duration for timeou... | 933460c | discord | python3.9 | e1c1a72a | diff --git a/discord/automod.py b/discord/automod.py
--- a/discord/automod.py
+++ b/discord/automod.py
@@ -135,6 +135,10 @@ class AutoModRuleAction:
raise ValueError('Only one of channel_id, duration, or custom_message can be passed.')
self.type: AutoModRuleActionType
+ self.channel_id: O... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_4 | python | import unittest
import datetime
import sys
class TestAutoModRuleAction(unittest.TestCase):
def test_send_alert_message_initialization(self):
from discord.automod import AutoModRuleAction, AutoModRuleActionType
action = AutoModRuleAction(type=AutoModRuleActionType.send_alert_message, channel_id=12... |
https://github.com/teamqurrent/discord.py | In `app_commands/commands.py`, modify the `Group` class's `__init__` method to include validation checks that ensure both name and description parameters are provided when creating a command group. Implement conditional logic to raise a TypeError if either of these essential attributes is missing, thereby enforcing the... | 576ab26 | discord | python3.9 | 55594035 | diff --git a/discord/app_commands/commands.py b/discord/app_commands/commands.py
--- a/discord/app_commands/commands.py
+++ b/discord/app_commands/commands.py
@@ -1548,6 +1548,9 @@ class Group:
if not self.description:
raise TypeError('groups must have a description')
+ if not self.name:
... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_5 | python | import unittest
import sys
class TestCommandGroupInitialization(unittest.TestCase):
def test_group_initialization_without_name(self):
from discord.app_commands import Group
with self.assertRaises(TypeError):
Group(description="Test Description", parent=None)
def test_group_initia... |
https://github.com/teamqurrent/discord.py | Enhance the discord.py library by adding a remove_dynamic_items method to the `Client`, `ConnectionState`, and `ViewStore` classes, enabling the removal of registered DynamicItem classes from persistent listening. In `client.py`, implement remove_dynamic_items in the `Client` class to validate and pass dynamic item cla... | 4182306 | discord | python3.9 | 7c3868ef | diff --git a/discord/client.py b/discord/client.py
--- a/discord/client.py
+++ b/discord/client.py
@@ -2681,7 +2681,7 @@ class Client:
return state.add_dm_channel(data)
def add_dynamic_items(self, *items: Type[DynamicItem[Item[Any]]]) -> None:
- r"""Registers a :class:`~discord.ui.DynamicItem` cl... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_6 | python | import unittest
import sys
from discord.ui import DynamicItem, Item
class MockDynamicItem(DynamicItem, Item, template='mock_template'):
pass
class TestClientDynamicItems(unittest.TestCase):
def setUp(self):
from discord import Client, Intents
from unittest.mock import MagicMock
inte... |
https://github.com/teamqurrent/discord.py | In the discord.py repository, refactor the `Template` class in `template.py` to streamline the initialization of the source_guild attribute. Remove the conditional logic that checks for an existing guild and instead always initialize source_guild from the serialized guild data. Additionally, add a cache_guild_expressio... | 8b8ce55 | discord | python3.9 | 16f6466d | diff --git a/discord/template.py b/discord/template.py
--- a/discord/template.py
+++ b/discord/template.py
@@ -69,6 +69,10 @@ class _PartialTemplateState:
def member_cache_flags(self):
return self.__state.member_cache_flags
+ @property
+ def cache_guild_expressions(self):
+ return False
+
... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_7 | python | import unittest
import sys
import os
# Mocking _PartialTemplateState as it is not importable easily
class MockPartialTemplateState:
def __init__(self, state):
from unittest.mock import MagicMock
self.__state = state
self.user = state.user
self.member_cache_flags = MagicMo... |
https://github.com/teamqurrent/discord.py | To align with new guild event permissions in Discord, modify the `Permissions` class in `discord/permissions.py`. Add a events class method to initialize a `Permissions` object with event-related permissions set (using the specific bit pattern of 0b100000000001000000000000000000000000000000000). Also, implement a creat... | 135e57c | discord | python3.9 | c69ce78a | diff --git a/discord/permissions.py b/discord/permissions.py
--- a/discord/permissions.py
+++ b/discord/permissions.py
@@ -329,6 +329,15 @@ class Permissions(BaseFlags):
"""
return cls(0b10000010001110000000000000010000000111110)
+ @classmethod
+ def events(cls) -> Self:
+ """A factory ... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_8 | python | import unittest
import sys
class TestPermissionsEvents(unittest.TestCase):
def test_events_class_method(self):
from discord.permissions import Permissions
perms = Permissions.events()
self.assertTrue(perms.create_events)
def test_create_events_property(self):
from discord.pe... |
https://github.com/teamqurrent/discord.py | In the `AuditLogEntry` class within `discord/audit_logs.py`, modify the `_convert_target_user` method to handle scenarios where target_id is None. Ensure that in such cases, the method initializes and returns a default user representation or a suitable placeholder object, instead of returning None. This change should e... | 0adef0e | discord | python3.9 | cb6170a7 | diff --git a/discord/audit_logs.py b/discord/audit_logs.py
--- a/discord/audit_logs.py
+++ b/discord/audit_logs.py
@@ -733,12 +733,11 @@ class AuditLogEntry(Hashable):
if self.action.target_type is None:
return None
- if self._target_id is None:
- return None
-
try:
... | [
{
"content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-present Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nth... | 10_9 | python | import unittest
import sys
class TestAuditLogEntryTarget(unittest.TestCase):
def setUp(self):
from discord.audit_logs import AuditLogEntry
from discord import enums
from unittest.mock import MagicMock
# Mocking the required arguments for AuditLogEntry
mock_guild = MagicMoc... |
https://github.com/teamqurrent/prowler | The goal is to correct a reference issue in the `__init__` method of a specific class within the `service.py` file, located in the `prowler/providers/gcp/lib/service` directory. The task involves ensuring that the `__generate_client__` method is called with the class's own service attribute, rather than an external ser... | cd03fa6 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | 1737d7cf | diff --git a/prowler/providers/gcp/lib/service/service.py b/prowler/providers/gcp/lib/service/service.py
--- a/prowler/providers/gcp/lib/service/service.py
+++ b/prowler/providers/gcp/lib/service/service.py
@@ -27,7 +27,7 @@ class GCPService:
self.default_project_id = audit_info.default_project_id
sel... | [
{
"content": "import threading\n\nimport google_auth_httplib2\nimport httplib2\nfrom colorama import Fore, Style\nfrom google.oauth2.credentials import Credentials\nfrom googleapiclient import discovery\nfrom googleapiclient.discovery import Resource\n\nfrom prowler.lib.logger import logger\nfrom prowler.provid... | 11_0 | python | import unittest
import os
import sys
import ast
class ArgExtractor(ast.NodeVisitor):
def __init__(self):
self.arguments = []
self.in_gcp_service_class = False
def visit_ClassDef(self, node):
if node.name == 'GCPService':
self.in_gcp_service_class = True
self.... |
https://github.com/teamqurrent/prowler | The goal is to to enhance the `__get_insight_selectors__` method in the `cloudtrail_service.py` file of the `Cloudtrail` class. Specifically, add conditional checks within the exception handling block to identify InsightNotEnabledException and UnsupportedOperationException exceptions. For these exceptions, log a detail... | 4785056 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | 44a4c067 | diff --git a/prowler/providers/aws/services/cloudtrail/cloudtrail_service.py b/prowler/providers/aws/services/cloudtrail/cloudtrail_service.py
--- a/prowler/providers/aws/services/cloudtrail/cloudtrail_service.py
+++ b/prowler/providers/aws/services/cloudtrail/cloudtrail_service.py
@@ -140,7 +140,16 @@ class Cloudtrail... | [
{
"content": "from datetime import datetime\nfrom typing import Optional\n\nfrom botocore.client import ClientError\nfrom pydantic import BaseModel\n\nfrom prowler.lib.logger import logger\nfrom prowler.lib.scan_filters.scan_filters import is_resource_filtered\nfrom prowler.providers.aws.lib.service.service imp... | 11_1 | python | import unittest
import sys
from unittest.mock import patch, Mock, ANY
class TestCloudtrail(unittest.TestCase):
def setUp(self):
from prowler.providers.aws.services.cloudtrail.cloudtrail_service import Cloudtrail
self.audit_info_mock = Mock()
self.audit_info_mock.audited_partition = 'aws'
... |
https://github.com/teamqurrent/prowler | you need to move the `generate_client` function from `gcp_provider.py` to the `GCPService` class in `service.py`, renaming it to `__generate_client__`. This involves adapting the function to work as a method within the `GCPService` class and updating all references in the two files to use this new method. Ensure that t... | bf0e62a | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | ed33fac3 | diff --git a/prowler/providers/gcp/gcp_provider.py b/prowler/providers/gcp/gcp_provider.py
--- a/prowler/providers/gcp/gcp_provider.py
+++ b/prowler/providers/gcp/gcp_provider.py
@@ -3,10 +3,8 @@ import sys
from google import auth
from googleapiclient import discovery
-from googleapiclient.discovery import Resource... | [
{
"content": "import os\nimport sys\n\nfrom google import auth\nfrom googleapiclient import discovery\nfrom googleapiclient.discovery import Resource\n\nfrom prowler.lib.logger import logger\nfrom prowler.providers.gcp.lib.audit_info.models import GCP_Audit_Info\n\n\nclass GCP_Provider:\n def __init__(\n ... | 11_2 | python | import unittest
import sys
from unittest.mock import patch, Mock
class TestGCPServiceClientGeneration(unittest.TestCase):
def setUp(self):
from prowler.providers.gcp.lib.service.service import GCPService
from google.oauth2.credentials import Credentials
self.audit_info_mock = Mock()
... |
https://github.com/teamqurrent/prowler | Your objective is refining the handling of FMS policies in `fms_policy_compliant.py` and `fms_service.py`. In `fms_policy_compliant.py`, enhance the execute method to correctly identify and report scenarios with no FMS policies, marking them as failures. In `fms_service.py`, update the `__list_compliance_status__` meth... | d1bd097 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | 423f96b9 | diff --git a/prowler/providers/aws/services/fms/fms_policy_compliant/fms_policy_compliant.py b/prowler/providers/aws/services/fms/fms_policy_compliant/fms_policy_compliant.py
--- a/prowler/providers/aws/services/fms/fms_policy_compliant/fms_policy_compliant.py
+++ b/prowler/providers/aws/services/fms/fms_policy_complia... | [
{
"content": "from prowler.lib.check.models import Check, Check_Report_AWS\nfrom prowler.providers.aws.services.fms.fms_client import fms_client\n\n\nclass fms_policy_compliant(Check):\n def execute(self):\n findings = []\n if fms_client.fms_admin_account:\n report = Check_Report_AWS... | 11_3 | python | from unittest import mock
import sys
import unittest
class Test_fms_policy_compliant(unittest.TestCase):
def test_fms_admin_without_policies(self):
from tests.providers.aws.audit_info_utils import (
AWS_ACCOUNT_NUMBER,
AWS_REGION_US_EAST_1,
)
fms_client = mock.Mag... |
https://github.com/teamqurrent/prowler | To improve readability, focus on converting string concatenations to f-string format in the following specific functions and files: `get_azure_html_assessment_summary` in `html.py`, both `send_slack_message` and `create_message_identity` in `slack.py`, `execute` in `apigateway_restapi_authorizers_enabled.py`, `print_az... | 0fff056 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | ceabe8ec | diff --git a/prowler/lib/outputs/html.py b/prowler/lib/outputs/html.py
--- a/prowler/lib/outputs/html.py
+++ b/prowler/lib/outputs/html.py
@@ -407,7 +407,7 @@ def get_azure_html_assessment_summary(audit_info):
if isinstance(audit_info, Azure_Audit_Info):
printed_subscriptions = []
for... | [
{
"content": "import importlib\nimport sys\nfrom os import path\n\nfrom prowler.config.config import (\n html_file_suffix,\n html_logo_img,\n html_logo_url,\n prowler_version,\n timestamp,\n)\nfrom prowler.lib.check.models import Check_Report_AWS, Check_Report_GCP\nfrom prowler.lib.logger import ... | 11_4 | python | import unittest
import sys
class TestFStringFormatting(unittest.TestCase):
def test_html_py(self):
self.assert_f_string_format("prowler/lib/outputs/html.py", [410])
def test_slack_py(self):
self.assert_f_string_format("prowler/lib/outputs/slack.py", [16, 38])
def test_apigateway_restap... |
https://github.com/teamqurrent/prowler | You will need to streamline the allowlist checking logic in `allowlist.py` and update the regional constants in `audit_info_utils.py`. In `allowlist.py`, modify the `is_allowlisted` function to iterate over all accounts in the allowlist and simplify the logic to check if a finding is allowlisted. Also, refine the is_ex... | 10e8222 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | 0fff0568 | diff --git a/prowler/providers/aws/lib/allowlist/allowlist.py b/prowler/providers/aws/lib/allowlist/allowlist.py
--- a/prowler/providers/aws/lib/allowlist/allowlist.py
+++ b/prowler/providers/aws/lib/allowlist/allowlist.py
@@ -143,29 +143,23 @@ def is_allowlisted(
finding_tags,
):
try:
- allowlisted_c... | [
{
"content": "import re\nimport sys\nfrom typing import Any\n\nimport yaml\nfrom boto3.dynamodb.conditions import Attr\nfrom schema import Optional, Schema\n\nfrom prowler.lib.logger import logger\nfrom prowler.lib.outputs.models import unroll_tags\n\nallowlist_schema = Schema(\n {\n \"Accounts\": {\n... | 11_5 | python | import unittest
import sys
class Test_Allowlist(unittest.TestCase):
def test_is_allowlisted_all_and_single_account_with_different_resources(self):
from prowler.providers.aws.lib.allowlist.allowlist import (
is_allowlisted,
is_excepted,
)
from tests.providers.aws.au... |
https://github.com/teamqurrent/prowler | Youre goal is to validate incoming s3 bucket names. Create the validate_bucket function in `arguments.py`, which uses a specific regex to validate AWS S3 bucket names as per AWS's naming rules. The regex should check that the bucket name does not start with 'xn--' or end with '-s3alias', starts with a lowercase letter ... | fdeb523 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | c8831f0f | diff --git a/prowler/providers/aws/lib/arguments/arguments.py b/prowler/providers/aws/lib/arguments/arguments.py
--- a/prowler/providers/aws/lib/arguments/arguments.py
+++ b/prowler/providers/aws/lib/arguments/arguments.py
@@ -1,4 +1,5 @@
from argparse import ArgumentTypeError, Namespace
+from re import search
from... | [
{
"content": "from argparse import ArgumentTypeError, Namespace\n\nfrom prowler.providers.aws.aws_provider import get_aws_available_regions\nfrom prowler.providers.aws.lib.arn.arn import arn_type\n\n\ndef init_parser(self):\n \"\"\"Init the AWS Provider CLI parser\"\"\"\n aws_parser = self.subparsers.add_... | 11_6 | python | import unittest
import sys
from unittest.mock import patch
# import pytest
prowler_command = "prowler"
# capsys
# https://docs.pytest.org/en/7.1.x/how-to/capture-stdout-stderr.html
prowler_default_usage_error = "usage: prowler [-h] [-v] {aws,azure,gcp} ..."
def mock_get_available_providers():
return ["aws", "... |
https://github.com/teamqurrent/prowler | Your objective is to introduce a new command-line argument --send-sh-only-fails to Prowler's AWS Security Hub integration. You need to modify `arguments.py`, `security_hub.py`, and `outputs.py`. In `arguments.py`, add a new command-line argument --send-sh-only-fails to the AWS Security Hub parser. In `security_hub.py`,... | 9a86846 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | fdeb5235 | diff --git a/prowler/providers/aws/lib/arguments/arguments.py b/prowler/providers/aws/lib/arguments/arguments.py
--- a/prowler/providers/aws/lib/arguments/arguments.py
+++ b/prowler/providers/aws/lib/arguments/arguments.py
@@ -84,6 +84,11 @@ def init_parser(self):
action="store_true",
help="Skip updat... | [
{
"content": "from argparse import ArgumentTypeError, Namespace\n\nfrom prowler.providers.aws.aws_provider import get_aws_available_regions\nfrom prowler.providers.aws.lib.arn.arn import arn_type\n\n\ndef init_parser(self):\n \"\"\"Init the AWS Provider CLI parser\"\"\"\n aws_parser = self.subparsers.add_... | 11_7 | python | import unittest
import sys
from unittest.mock import patch
prowler_command = "prowler"
# capsys
# https://docs.pytest.org/en/7.1.x/how-to/capture-stdout-stderr.html
prowler_default_usage_error = "usage: prowler [-h] [-v] {aws,azure,gcp} ..."
def mock_get_available_providers():
return ["aws", "azure", "gcp"]
c... |
https://github.com/teamqurrent/prowler | The objective is to revert the feature that automatically cleans up local output directories after Prowler sends output to remote storage. Remove the `clean.py` file from the common directory and eliminate any references to its functions, particularly `clean_provider_local_output_directories`, from the Prowler main fil... | 9099bd7 | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | fdcc2ac5 | diff --git a/prowler/__main__.py b/prowler/__main__.py
--- a/prowler/__main__.py
+++ b/prowler/__main__.py
@@ -51,7 +51,6 @@ from prowler.providers.common.audit_info import (
set_provider_audit_info,
set_provider_execution_parameters,
)
-from prowler.providers.common.clean import clean_provider_local_output_... | [
{
"content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nfrom colorama import Fore, Style\n\nfrom prowler.lib.banner import print_banner\nfrom prowler.lib.check.check import (\n bulk_load_checks_metadata,\n bulk_load_compliance_frameworks,\n exclude_checks_to_run,\n ... | 11_8 | python | import unittest
import os
import sys
from importlib import import_module
class TestProwlerCommitChanges(unittest.TestCase):
def test_clean_module_removal(self):
self.assertFalse(os.path.exists('prowler/providers/common/clean.py'))
def test_clean_test_module_removal(self):
self.assertFalse(o... |
https://github.com/teamqurrent/prowler | Your objective is to refine the checks in the AWS GuardDuty service integration. Specifically, the changes involve updating the `guardduty_centrally_managed.py` and `guardduty_no_high_severity_findings.py` files to enhance the logic used in evaluating GuardDuty detectors. Specifically your update should refine the cond... | f8e713a | about-time==4.2.1 ; python_version >= "3.9" and python_version < "3.12" \
--hash=sha256:6a538862d33ce67d997429d14998310e1dbfda6cb7d9bbfbf799c4709847fece \
--hash=sha256:8bbf4c75fe13cbd3d72f49a03b02c5c7dca32169b6d49117c257e7eb3eaee341
adal==1.2.7 ; python_version >= "3.9" and python_version < "3.12" \
--hash... | python3.9 | 3a3bb44f | diff --git a/prowler/providers/aws/services/guardduty/guardduty_centrally_managed/guardduty_centrally_managed.py b/prowler/providers/aws/services/guardduty/guardduty_centrally_managed/guardduty_centrally_managed.py
--- a/prowler/providers/aws/services/guardduty/guardduty_centrally_managed/guardduty_centrally_managed.py... | [
{
"content": "from prowler.lib.check.models import Check, Check_Report_AWS\nfrom prowler.providers.aws.services.guardduty.guardduty_client import guardduty_client\n\n\nclass guardduty_centrally_managed(Check):\n def execute(self):\n findings = []\n for detector in guardduty_client.detectors:\n ... | 11_9 | python | import unittest
import sys
from unittest import mock
from uuid import uuid4
class Test_guardduty_centrally_managed(unittest.TestCase):
def test_not_enabled_account_detector(self):
from prowler.providers.aws.services.guardduty.guardduty_service import Detector
from tests.providers.aws.audit_info_... |
https://github.com/teamqurrent/aider | The aim is to improve the resilience of file reading operations in the `__init__` method of a class in `io.py` by enhancing its error handling capabilities. To achieve this, locate the section in the `__init__` method where files are opened and read. In this section, update the existing exception handling that catches ... | efb3f03 | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | f3d3815 | diff --git a/aider/io.py b/aider/io.py
--- a/aider/io.py
+++ b/aider/io.py
@@ -44,7 +44,7 @@ class AutoCompleter(Completer):
try:
with open(fname, "r", encoding=self.encoding) as f:
content = f.read()
- except FileNotFoundError:
+ except (FileNotF... | [
{
"content": "import os\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom prompt_toolkit.completion import Completer, Completion\nfrom prompt_toolkit.history import FileHistory\nfrom prompt_toolkit.key_binding import KeyBindings\nfrom prompt_toolkit.lexers imp... | 12_0 | python | import unittest
import sys
from unittest.mock import patch
class TestInputOutput(unittest.TestCase):
def test_autocompleter_with_unicode_file(self):
from tests.utils import ChdirTemporaryDirectory
from pathlib import Path
from aider.io import AutoCompleter
with ChdirTem... |
https://github.com/teamqurrent/aider | In the `cmd_add` method of the `Commands` class in `commands.py`, you need to adjust how the method identifies if a file is already tracked in the Git repository. Start by calculating the relative path of each file being processed, using self.coder.get_rel_fname(matched_file), and store this in a variable named rel_pat... | 2609ec1 | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | d720bfe | diff --git a/aider/commands.py b/aider/commands.py
--- a/aider/commands.py
+++ b/aider/commands.py
@@ -305,6 +305,7 @@ class Commands:
for matched_file in all_matched_files:
abs_file_path = self.coder.abs_root_path(matched_file)
+ rel_path = self.coder.get_rel_fname(matched_file)
... | [
{
"content": "import json\nimport re\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport git\nfrom prompt_toolkit.completion import Completion\n\nfrom aider import prompts, voice\n\nfrom .dump import dump # noqa: F401\n\n\nclass Commands:\n voice = None\n\n def __init__(self, io, coder, vo... | 12_1 | python | import os
import unittest
import shutil
import sys
import tempfile
from pathlib import Path
from unittest import TestCase
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
def tearDown(self):
... |
https://github.com/teamqurrent/aider | Your goal is to update the dname path from 'tmp.benchmarks/refactor-benchmark-pylint' to 'tmp.benchmarks/refactor-benchmark-spyder' in function process(entry) in the `refactor_tools.py` file | d9a301c | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | ef2a1f3 | diff --git a/aider/coders/editblock_prompts.py b/aider/coders/editblock_prompts.py
--- a/aider/coders/editblock_prompts.py
+++ b/aider/coders/editblock_prompts.py
@@ -174,6 +174,8 @@ Include *ALL* the code being searched and replaced!
Only *SEARCH/REPLACE* files that are *read-write*.
+To move code within a file, ... | [
{
"content": "# flake8: noqa: E501\n\nfrom .base_prompts import CoderPrompts\n\n\nclass EditBlockPrompts(CoderPrompts):\n main_system = \"\"\"Act as an expert software developer.\nYou are diligent and tireless!\nYou NEVER leave comments describing code without implementing it!\nYou always COMPLETELY IMPLEMEN... | 12_2 | python | import unittest
import sys
from pathlib import Path
class TestRefactorTools(unittest.TestCase):
def test_directory_name_change(self):
file_path = Path('benchmark/refactor_tools.py')
with open(file_path, 'r') as file:
lines = file.readlines()
# Check if the line 160 contains ... |
https://github.com/teamqurrent/aider | In the openai.py model file, we need to avoid swamping the model with too much context. in the `__init__` function of the file, reduce the max_chat_history_tokens for elif cases of 32 tokens and 128 tokens to '2 * 1024'. Also do the same reduction of max_chat_history_tokens for the gpt-3.5-turbo-1106 model. Doing so sh... | 560759f | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | 92f4100 | diff --git a/aider/models/openai.py b/aider/models/openai.py
--- a/aider/models/openai.py
+++ b/aider/models/openai.py
@@ -44,11 +44,11 @@ class OpenAIModel(Model):
elif tokens == 32:
self.prompt_price = 0.06
self.completion_price = 0.12
- self.max_chat_hist... | [
{
"content": "import re\n\nimport tiktoken\n\nfrom .model import Model\n\nknown_tokens = {\n \"gpt-3.5-turbo\": 4,\n \"gpt-4\": 8,\n \"gpt-4-1106-preview\": 128,\n \"gpt-3.5-turbo-1106\": 16,\n}\n\n\nclass OpenAIModel(Model):\n def __init__(self, name):\n self.name = name\n\n tokens... | 12_3 | python | import unittest
import sys
from pathlib import Path
class TestOpenAiModel(unittest.TestCase):
def test_max_chat_history_tokens_update(self):
file_path = Path('aider/models/openai.py')
with open(file_path, 'r') as file:
lines = file.readlines()
buffer = 1 # Number of lines t... |
https://github.com/teamqurrent/aider | Your goal is to modify the `base_coder.py` file in the coders folder to show the repomap before the added files in the get_repo_map function. Find and move the relevant code block aassociated with the repo map and move it above the code for showing added files. | cab7460 | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | 560759f | diff --git a/aider/coders/base_coder.py b/aider/coders/base_coder.py
--- a/aider/coders/base_coder.py
+++ b/aider/coders/base_coder.py
@@ -311,6 +311,13 @@ class Coder:
def get_files_messages(self):
all_content = ""
+
+ repo_content = self.get_repo_map()
+ if repo_content:
+ if ... | [
{
"content": "#!/usr/bin/env python\n\nimport hashlib\nimport json\nimport os\nimport sys\nimport threading\nimport time\nimport traceback\nfrom json.decoder import JSONDecodeError\nfrom pathlib import Path\n\nimport openai\nfrom jsonschema import Draft7Validator\nfrom rich.console import Console, Text\nfrom ri... | 12_4 | python | import unittest
import sys
from pathlib import Path
class TestCodeBlockMovement(unittest.TestCase):
def test_code_block_moved(self):
file_path = Path('aider/coders/base_coder.py')
with open(file_path, 'r') as file:
lines = file.readlines()
expected_block = [
... |
https://github.com/teamqurrent/aider | You need to modify the `cmd_add` method in the `Commands` class within `commands.py`. Specifically, replace args.split() with shlex.split(args) to correctly handle quoted filenames. Additionally, update the file existence check to ensure that filenames with spaces are correctly identified and added to all_matched_files... | d2acb8e | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | 774589b | diff --git a/aider/commands.py b/aider/commands.py
--- a/aider/commands.py
+++ b/aider/commands.py
@@ -272,13 +272,12 @@ class Commands:
git_files = self.coder.repo.get_tracked_files() if self.coder.repo else []
all_matched_files = set()
- for word in args.split():
+ for word in shlex.... | [
{
"content": "import json\nimport shlex\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport git\nfrom prompt_toolkit.completion import Completion\n\nfrom aider import prompts, voice\n\nfrom .dump import dump # noqa: F401\n\n\nclass Commands:\n voice = None\n\n def __init__(self, io, coder,... | 12_5 | python | import os
import shutil
import sys
import tempfile
import unittest
import sys
from pathlib import Path
from unittest import TestCase
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
def tearDown(se... |
https://github.com/teamqurrent/aider | The objective is to refine the `commands.py` `cmd_add` method's handling of file paths and patterns. The goal is to streamline the process of adding files to all_matched_files by simplifying the logic for checking file existence and handling file patterns. The changes involve restructuring the code to make it more effi... | 399d86d | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | dc19a1f | diff --git a/aider/commands.py b/aider/commands.py
--- a/aider/commands.py
+++ b/aider/commands.py
@@ -273,25 +273,21 @@ class Commands:
all_matched_files = set()
for word in args.split():
+ fname = Path(self.coder.root) / word
+ if fname.exists():
+ if fname.is_... | [
{
"content": "import json\nimport shlex\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport git\nfrom prompt_toolkit.completion import Completion\n\nfrom aider import prompts, voice\n\nfrom .dump import dump # noqa: F401\n\n\nclass Commands:\n voice = None\n\n def __init__(self, io, coder,... | 12_6 | python | import os
import shutil
import sys
import unittest
import tempfile
from pathlib import Path
from unittest import TestCase
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
def tearDown(self):
... |
https://github.com/teamqurrent/aider | The objective of this commit is to enhance the security and integrity of the `cmd_add` method in the `Commands` class within `commands.py`. Specifically, the goal is to prevent the addition of files that are located outside the designated coder.root directory. This is to ensure that only files within the specified root... | 5d7e440 | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | 399d86d | diff --git a/aider/commands.py b/aider/commands.py
--- a/aider/commands.py
+++ b/aider/commands.py
@@ -296,6 +296,12 @@ class Commands:
for matched_file in all_matched_files:
abs_file_path = self.coder.abs_root_path(matched_file)
+ if not abs_file_path.startswith(self.coder.root):
+ ... | [
{
"content": "import json\nimport shlex\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport git\nfrom prompt_toolkit.completion import Completion\n\nfrom aider import prompts, voice\n\nfrom .dump import dump # noqa: F401\n\n\nclass Commands:\n voice = None\n\n def __init__(self, io, coder,... | 12_7 | python | import os
import shutil
import sys
import unittest
import tempfile
from pathlib import Path
from unittest import TestCase
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
def tearDown(self):
... |
https://github.com/teamqurrent/aider | The objective of is to fix an issue in the `cmd_add` method of the `Commands` class within `commands.py`, specifically when adding files from a subdirectory. The goal is to ensure that file paths are correctly resolved relative to the coder.root directory, and the method can handle file creation and addition without er... | 545f105 | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | 98bacd0 | diff --git a/aider/commands.py b/aider/commands.py
--- a/aider/commands.py
+++ b/aider/commands.py
@@ -279,16 +279,17 @@ class Commands:
if any(char in word for char in "*?[]"):
self.io.tool_error(f"No files to add matching pattern: {word}")
else:
- ... | [
{
"content": "import json\nimport shlex\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport git\nfrom prompt_toolkit.completion import Completion\n\nfrom aider import prompts, voice\n\nfrom .dump import dump # noqa: F401\n\n\nclass Commands:\n voice = None\n\n def __init__(self, io, coder,... | 12_8 | python |
import os
import shutil
import sys
import unittest
import tempfile
from pathlib import Path
from unittest import TestCase
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
def tearDown(self):
... |
https://github.com/teamqurrent/aider | Your objective is in `commands.py`, refine the `cmd_drop` method in the `Commands` class to ensure consistent and accurate path resolution for files being removed. The goal is to standardize the way file paths are resolved within the method, using a specific function from the coder object, thereby ensuring that file pa... | d785d9a | aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==23.1.0
certifi==2023.5.7
charset-normalizer==3.1.0
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
markdown-it-py==2.2.0
mdurl==0.1.2
multidict==6.0.4
openai==0.27.6
prompt-toolkit==3.0.38
Pygments==2.15.1
requests==2.30.0
rich==13.3.5
smmap==5.0.0... | python3.9 | 450a5ff | diff --git a/aider/commands.py b/aider/commands.py
--- a/aider/commands.py
+++ b/aider/commands.py
@@ -328,7 +328,7 @@ class Commands:
self.io.tool_error(f"No files matched '{word}'")
for matched_file in matched_files:
- abs_fname = str(Path(matched_file).resolve())
+ ... | [
{
"content": "import json\nimport shlex\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nimport git\nimport tiktoken\nfrom prompt_toolkit.completion import Completion\n\nfrom aider import prompts\n\nfrom .dump import dump # noqa: F401\n\n\nclass Commands:\n def __init__(self, io, coder):\n ... | 12_9 | python | import os
import shutil
import sys
import unittest
import tempfile
from pathlib import Path
from unittest import TestCase
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
def tearDown(self):
... |
https://github.com/teamqurrent/requests | Your objective is improving the validation of header parts (name and value) by refining the way these parts are checked against their respective types (str or bytes) and their format. The key files involved are `requests/_internal_utils.py` and `requests/utils.py`. The primary functions to modify or focus on are `_vali... | e90852d | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 7f694b79 | diff --git a/requests/_internal_utils.py b/requests/_internal_utils.py
--- a/requests/_internal_utils.py
+++ b/requests/_internal_utils.py
@@ -14,9 +14,11 @@ _VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")
_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")
_VALID_HEADER_VALUE_RE_STR = re.compi... | [
{
"content": "\"\"\"\nrequests._internal_utils\n~~~~~~~~~~~~~~\n\nProvides utility functions that are consumed internally by Requests\nwhich depend on extremely few external helpers (such as compat)\n\"\"\"\nimport re\n\nfrom .compat import builtin_str\n\n_VALID_HEADER_NAME_RE_BYTE = re.compile(rb\"^[^:\\s][^:\... | 13_0 | python | import sys
import pytest
import requests
# Requests to this URL should always fail with a connection timeout (nothing
# listening on that port)
TARPIT = "http://10.255.255.1"
# This is to avoid waiting the timeout of using TARPIT
INVALID_PROXY = "http://localhost:1"
class TestRequests:
try:
from ssl i... |
https://github.com/teamqurrent/requests | Your objective is enhancing the validation of HTTP headers in the requests library. The primary goal is to ensure that header names and values do not contain leading whitespace, reserved characters, or return characters, which could lead to security vulnerabilities like header injection. The key files to modify are `re... | 60865f2 | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | e36f3459 | diff --git a/requests/_internal_utils.py b/requests/_internal_utils.py
--- a/requests/_internal_utils.py
+++ b/requests/_internal_utils.py
@@ -5,9 +5,20 @@ requests._internal_utils
Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
"""
... | [
{
"content": "\"\"\"\nrequests._internal_utils\n~~~~~~~~~~~~~~\n\nProvides utility functions that are consumed internally by Requests\nwhich depend on extremely few external helpers (such as compat)\n\"\"\"\n\nfrom .compat import builtin_str\n\n\ndef to_native_string(string, encoding=\"ascii\"):\n \"\"\"Give... | 13_1 | python | import sys
import pytest
# Requests to this URL should always fail with a connection timeout (nothing
# listening on that port)
TARPIT = "http://10.255.255.1"
# This is to avoid waiting the timeout of using TARPIT
INVALID_PROXY = "http://localhost:1"
class TestRequests:
import requests
from requests.excep... |
https://github.com/teamqurrent/requests | Your objective is to improve the exception handling in the requests library, specifically targeting the handling of SSL errors. The goal is to ensure that SSL errors from the urllib3 library are correctly wrapped and re-raised as requests.exceptions.SSLError within the requests library. This change is crucial for maint... | 7ae3887 | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 95f45673 | diff --git a/HISTORY.md b/HISTORY.md
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -6,6 +6,11 @@ dev
- \[Short description of non-trivial change.\]
+**Bugfixes**
+
+- Fixed urllib3 exception leak, wrapping `urllib3.exceptions.SSLError` with
+ `requests.exceptions.SSLError` for `content` and `iter_content`.
+
2.27.1 (2022... | [
{
"content": "Release History\n===============\n\ndev\n---\n\n- \\[Short description of non-trivial change.\\]\n\n2.27.1 (2022-01-05)\n-------------------\n\n**Bugfixes**\n\n- Fixed parsing issue that resulted in the `auth` component being\n dropped from proxy URLs. (#6028)\n\n2.27.0 (2022-01-03)\n------------... | 13_2 | python | import sys
import urllib3
import pytest
# Requests to this URL should always fail with a connection timeout (nothing
# listening on that port)
TARPIT = "http://10.255.255.1"
# This is to avoid waiting the timeout of using TARPIT
INVALID_PROXY = "http://localhost:1"
class TestRequests:
from unittest import mo... |
https://github.com/teamqurrent/requests | Your objective is to to enhance the way the requests library handles SSL certificate bundle settings from environment variables. Specifically, focus on improving the `merge_environment_settings` function in `requests/sessions.py` to better handle the REQUESTS_CA_BUNDLE and CURL_CA_BUNDLE environment variables. The goal... | 5e74954 | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 79c4a017 | diff --git a/requests/sessions.py b/requests/sessions.py
--- a/requests/sessions.py
+++ b/requests/sessions.py
@@ -702,11 +702,14 @@ class Session(SessionRedirectMixin):
for (k, v) in env_proxies.items():
proxies.setdefault(k, v)
- # Look for requests environment configuration... | [
{
"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.sessions\n~~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\"\"\"\nimport os\nimport sys\nimport time\nfrom datetime import timedelta\nfrom collections import OrderedDic... | 13_3 | python | import sys
import pytest
from unittest import mock
# Requests to this URL should always fail with a connection timeout (nothing
# listening on that port)
TARPIT = "http://10.255.255.1"
# This is to avoid waiting the timeout of using TARPIT
INVALID_PROXY = "http://localhost:1"
class TestRequests:
import reque... |
https://github.com/teamqurrent/requests | Your objective is to refine the exception handling in the requests library, particularly for JSON decoding errors. The goal is to modify the JSONDecodeError class in `requests/exceptions.py` to ensure that it properly inherits and integrates the functionalities of both InvalidJSONError from requests and JSONDecodeError... | d15a3b6 | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | fa1b0a36 | diff --git a/requests/exceptions.py b/requests/exceptions.py
--- a/requests/exceptions.py
+++ b/requests/exceptions.py
@@ -34,6 +34,16 @@ class InvalidJSONError(RequestException):
class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
"""Couldn't decode the text into json"""
+ def __init__(self, *ar... | [
{
"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.exceptions\n~~~~~~~~~~~~~~~~~~~\n\nThis module contains the set of Requests' exceptions.\n\"\"\"\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\n\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\n\nclass RequestException(IOErro... | 13_4 | python | import sys
import pytest
# Requests to this URL should always fail with a connection timeout (nothing
# listening on that port)
TARPIT = "http://10.255.255.1"
# This is to avoid waiting the timeout of using TARPIT
INVALID_PROXY = "http://localhost:1"
class TestRequests:
from requests.exceptions import (
... |
https://github.com/teamqurrent/requests | Your objective is to enhance the proxy handling in the requests library. Start by creating a `resolve_proxies` function in `requests/utils.py` that intelligently resolves proxies based on the request and environment settings. Then, in `requests/sessions.py`, update the Session.send method to use this new function for d... | 590350f | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 99b3b49 | diff --git a/requests/sessions.py b/requests/sessions.py
--- a/requests/sessions.py
+++ b/requests/sessions.py
@@ -29,7 +29,7 @@ from .adapters import HTTPAdapter
from .utils import (
requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,
- get_auth_from_url, rewind_body
+ get_auth_from_... | [
{
"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.sessions\n~~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\"\"\"\nimport os\nimport sys\nimport time\nfrom datetime import timedelta\nfrom collections import OrderedDic... | 13_5 | python | import sys
import pytest
# Requests to this URL should always fail with a connection timeout (nothing
# listening on that port)
TARPIT = "http://10.255.255.1"
# This is to avoid waiting the timeout of using TARPIT
INVALID_PROXY = "http://localhost:1"
class TestRequests:
from requests.exceptions import (
... |
https://github.com/teamqurrent/requests | Your objective should focus on correctly handling URLs with authentication information in the `prepend_scheme_if_needed` function in `requests/utils.py`. Update the function to check for the presence of auth in the parsed URL and, if present, correctly include it in the netloc. This approach ensures that URLs with auth... | 0192aac | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 38f3f8ec | diff --git a/requests/utils.py b/requests/utils.py
--- a/requests/utils.py
+++ b/requests/utils.py
@@ -974,6 +974,10 @@ def prepend_scheme_if_needed(url, new_scheme):
if not netloc:
netloc, path = path, netloc
+ if auth:
+ # parse_url doesn't provide the netloc with auth
+ # so we'll ad... | [
{
"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.utils\n~~~~~~~~~~~~~~\n\nThis module provides utility functions that are used within Requests\nthat are also useful for external consumption.\n\"\"\"\n\nimport codecs\nimport contextlib\nimport io\nimport os\nimport re\nimport socket\nimport struct\nimpo... | 13_6 | python | import sys
import pytest
@pytest.mark.parametrize(
"value, expected",
(
(
'http://user:pass@example.com/path?query',
'http://user:pass@example.com/path?query'
),
(
'http://user@example.com/path?query',
'http://user@example.com/path?query... |
https://github.com/teamqurrent/requests | Focus on enhancing the error handling in the `super_len` function within `requests/utils.py`. Update the function to catch an AttributeError when attempting to use the fileno method on file-like objects. | e77dd8d | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 2d2447e2 | diff --git a/HISTORY.md b/HISTORY.md
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -11,6 +11,9 @@ dev
backwards compatible as it inherits from previously thrown exceptions.
Can be caught from `requests.exceptions.RequestException` as well.
+- Catch `AttributeError` when calculating length of files obtained by
+ `Tarfil... | [
{
"content": "Release History\n===============\n\ndev\n---\n\n- \\[Short description of non-trivial change.\\]\n\n- Added a `requests.exceptions.JSONDecodeError` to decrease inconsistencies\n in the library. This gets raised in the `response.json()` method, and is\n backwards compatible as it inherits from pr... | 13_7 | python | import sys
import pytest
import tarfile
from io import BytesIO
def test_tarfile_member(tmpdir):
from requests.utils import super_len
file_obj = tmpdir.join('test.txt')
file_obj.write('Test')
tar_obj = str(tmpdir.join('test.tar'))
with tarfile.open(tar_obj, 'w') as tar:
tar.add(str(file_o... |
https://github.com/teamqurrent/requests | your goal is to update the URL parsing logic in the `prepend_scheme_if_needed` function within `requests/utils.py`. Start by importing parse_url from urllib3.util and use it to parse URLs more accurately. Handle cases where the netloc might be incorrectly interpreted by swapping it with path if necessary. Ensure that U... | 39d0fdd | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | ef59aa0 | diff --git a/requests/utils.py b/requests/utils.py
--- a/requests/utils.py
+++ b/requests/utils.py
@@ -21,6 +21,7 @@ import warnings
import zipfile
from collections import OrderedDict
from urllib3.util import make_headers
+from urllib3.util import parse_url
from .__version__ import __version__
from . import cert... | [
{
"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.utils\n~~~~~~~~~~~~~~\n\nThis module provides utility functions that are used within Requests\nthat are also useful for external consumption.\n\"\"\"\n\nimport codecs\nimport contextlib\nimport io\nimport os\nimport re\nimport socket\nimport struct\nimpo... | 13_8 | python | import sys
import pytest
@pytest.mark.parametrize(
"value, expected",
(
("example.com:80", "http://example.com:80"),
),
)
def test_prepend_scheme_if_needed(value, expected):
from requests.utils import prepend_scheme_if_needed
assert prepend_scheme_if_needed(value, "http") == expected
def... |
https://github.com/teamqurrent/requests | your goal is to update the `should_bypass_proxies` function in `requests/utils.py` to handle URLs without a hostname. After parsing the URL, add a condition to check if the hostname is None and, in such cases, return True to bypass proxies. This approach ensures that file:// URLs and similar non-standard URLs are corre... | dffd5d4 | -e .[socks]
pytest
pytest-cov
pytest-httpbin==1.0.0
pytest-mock
httpbin==0.7.0
trustme
wheel
chardet>=3.0.2,<3.1.0
idna>=2.5,<2.8
urllib3>=1.21.1,<1.24
certifi>=2017.4.17
# Flask Stack
Flask>1.0,<2.0
markupsafe<2.1
| python3.9 | 8023a01d | diff --git a/requests/utils.py b/requests/utils.py
--- a/requests/utils.py
+++ b/requests/utils.py
@@ -706,6 +706,10 @@ def should_bypass_proxies(url, no_proxy):
no_proxy = get_proxy('no_proxy')
parsed = urlparse(url)
+ if parsed.hostname is None:
+ # URLs don't always have hostnames, e.g. fil... | [
{
"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.utils\n~~~~~~~~~~~~~~\n\nThis module provides utility functions that are used within Requests\nthat are also useful for external consumption.\n\"\"\"\n\nimport codecs\nimport contextlib\nimport io\nimport os\nimport re\nimport socket\nimport struct\nimpo... | 13_9 | python | import sys
import pytest
@pytest.mark.parametrize(
"url, expected",
(
("file:///some/path/on/disk", True),
),
)
def test_should_bypass_proxies(url, expected, monkeypatch):
from requests.utils import should_bypass_proxies
"""Tests for function should_bypass_proxies to check if proxy
ca... |
https://github.com/teamqurrent/citrus | During querying if filters is None we should pass None to `filter_function`. Otherwise the function that is passed causes a bug without any filters present. Making changes in the `citrusdb/api/local.py` file should fix it. No need to run tests on the resulting script since the test environment is not ready yet | eb8fb28 | toml
numpy
hnswlib
| python3.9 | cb6878c | diff --git a/citrusdb/api/local.py b/citrusdb/api/local.py
--- a/citrusdb/api/local.py
+++ b/citrusdb/api/local.py
@@ -165,7 +165,7 @@ class LocalAPI:
documents=documents,
query_embeddings=query_embeddings,
k=k,
- filter_function=filter_f... | [
{
"content": "import os\nimport json\nfrom typing import Dict, List, Optional\nfrom numpy import float32\nfrom numpy._typing import NDArray\nimport shutil\n\nfrom citrusdb.api.index import Index\nfrom citrusdb.db.sqlite.db import DB\n\n\nclass LocalAPI:\n _db: Dict[str, Index] \n _sqlClient: DB\n persi... | 1_0 | python | import sys
import unittest
from unittest.mock import patch
class TestLocalAPIQuery(unittest.TestCase):
def test_query_with_none_filters(self):
from citrusdb.api.index import Index
from citrusdb.api.local import LocalAPI
api = LocalAPI()
api._db["mock_index"] = Index("mock_index")... |
https://github.com/teamqurrent/citrus | The cloud hosted version needs to be able to reload indices automatically on restart. Add a method to the local api to fetch metadata for all indices from the SQLite database and loads these indices to memory. What should be added: a reload_indices method to `citrusdb/api/local.py`, get_indices and get_index_details me... | 80bee4d | toml
numpy
hnswlib
| python3.9 | cb41ea8 | diff --git a/citrusdb/api/local.py b/citrusdb/api/local.py
--- a/citrusdb/api/local.py
+++ b/citrusdb/api/local.py
@@ -135,6 +135,25 @@ class LocalAPI:
self._db[index].delete_vectors(ids)
+ def reload_indices(self):
+ """
+ Load all indices from disk to memory
+ """
+
+ indic... | [
{
"content": "import os\nimport json\nfrom typing import Dict, List, Optional\nfrom numpy import float32\nfrom numpy._typing import NDArray\nimport shutil\n\nfrom citrusdb.api.index import Index\nfrom citrusdb.db.sqlite.db import DB\n\n\nclass LocalAPI:\n _db: Dict[str, Index] \n _sqlClient: DB\n persi... | 1_1 | python | import sys
import unittest
import inspect
class TestCitrusDbQueries(unittest.TestCase):
def test_queries_and_methods(self):
from citrusdb.api.local import LocalAPI
from citrusdb.db.sqlite.db import DB
from citrusdb.db.sqlite.queries import GET_ALL_INDEX_DETAILS
# Check if GET_ALL... |
https://github.com/teamqurrent/citrus | Update `pyproject.toml` and `setup.py` to update package version to 0.4.0. Also add psycopg[c] and psycopg[pool] to the list of packages that need to be installed in order for citrus to run properly. Lastly add citrusdb.db.postgres to the packages list after find_packages function call in `setup.py` | 8cf4263 | toml
numpy
hnswlib
| python3.9 | 7c58ccb | diff --git a/pyproject.toml b/pyproject.toml
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "citrusdb"
-version = "0.3.3"
+version = "0.4.0"
authors = [
{ name="Debabrata Mondal", email="debabrata.js@protonmail.com" },
@@ -17,6 +17,8 @@ dependencies = [
'hnswlib >= 0.7',
'numpy... | [
{
"content": "[project]\nname = \"citrusdb\"\nversion = \"0.3.3\"\n\nauthors = [\n { name=\"Debabrata Mondal\", email=\"debabrata.js@protonmail.com\" },\n]\ndescription = \"open-source vector database. store and retrieve embeddings for your next project!\"\nreadme = \"README.md\"\nrequires-python = \">=3.7\"\n... | 1_2 | python | import sys
import unittest
import ast
import toml
class TestTomlAndSetup(unittest.TestCase):
def test_toml_and_setup_file(self):
# Test toml file
parsed_toml = toml.load("pyproject.toml")
self.assertEqual(parsed_toml["project"]["version"], "0.4.0", "version wrong")
count = 0
... |
https://github.com/teamqurrent/citrus | Save the vector index after any vector is deleted. Update the corresponding method inside `citrusdb/api/index.py`. Only save the index if changes are to be persisted. | 9744caf | toml
numpy
hnswlib
| python3.9 | b0d0793 | diff --git a/citrusdb/api/index.py b/citrusdb/api/index.py
--- a/citrusdb/api/index.py
+++ b/citrusdb/api/index.py
@@ -80,6 +80,8 @@ class Index:
def delete_vectors(self, ids: List[int]):
for id in ids:
self._db.mark_deleted(id)
+ if self._parameters["persist_directory"]:
+ ... | [
{
"content": "import os\nimport pickle\nfrom typing import Any, List, Optional\nfrom numpy import float32\nfrom numpy._typing import NDArray\nfrom citrusdb.db.index.hnswlib import HnswIndex\nfrom citrusdb.utils.utils import ensure_valid_path\n\n\nclass Index:\n _db: HnswIndex\n _parameters: dict\n\n de... | 1_3 | python | import sys
import unittest
import ast
import inspect
import textwrap
class TestIndexDeleteVectors(unittest.TestCase):
def test_if_conditions_in_delete_vectors(self):
from citrusdb.api.index import Index
source = inspect.getsource(Index.delete_vectors)
source = textwrap.dedent(source)
... |
https://github.com/teamqurrent/citrus | Add a query to update ef value in `citrusdb/db/sqlite/queries.py` based on a given 'name'. Create an update_ef method in `citrusdb/db/sqlite/db.py` that uses the new UPDATE_EF query and takes in a name and an ef value as parameters. Add to the `set_ef` method in `citrusdb/api/local.py` to have it first set an ef value ... | 37a8258 | toml
numpy
hnswlib
| python3.9 | f525179 | diff --git a/citrusdb/api/local.py b/citrusdb/api/local.py
--- a/citrusdb/api/local.py
+++ b/citrusdb/api/local.py
@@ -26,7 +26,7 @@ class LocalAPI:
ef_construction: int = 200,
allow_replace_deleted: bool = False,
):
- if not(self._sqlClient.check_index_exists(name)):
+ if self.pers... | [
{
"content": "from citrusdb.api.index import Index\nfrom citrusdb.db.sqlite.db import DB\n\nfrom typing import Dict, List, Optional\nfrom numpy import float32\nfrom numpy._typing import NDArray\n\n\nclass LocalAPI:\n _db: Dict[str, Index] \n _sqlClient: DB\n persist_directory: Optional[str]\n\n def ... | 1_4 | python | import sys
import unittest
import inspect
class TestDatabaseAndQueries(unittest.TestCase):
def test_database_and_queries(self):
from citrusdb.api.local import LocalAPI
from citrusdb.db.sqlite.db import DB
from citrusdb.db.sqlite.queries import UPDATE_EF
# Checking for UPDATE_EF e... |
https://github.com/teamqurrent/citrus | The readme contains a few spelling mistakes. Update the readme with to fix them. | 23e65f5 | python3.9 | e7f33d8 | diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ You can directly pass vector embeddings as well. If you're passing a list of str
```py
result, distances = citrus.query("What is it like to launch a startup", k=1)
```
-Go launch a repl on [Replit](https://replit.com) and see what r... | [
{
"content": "# 🍋 citrus.\n### open-source (distributed) vector database\n\n<p align=\"center\">\n Special thanks to\n</p>\n<p align=\"center\">\n <img align=\"center\" src=\"https://www.getdevkit.com/logo.png\" width=100 height=100 alt=\"DevKit\" />\n</p>\n<p align=\"center\">\n <a href=\"https://www.getde... | 1_5 | python | import sys
import unittest
class TestReadmeTypos(unittest.TestCase):
def test_readme_for_typos(self):
# typos = ["runnig", "docuemnts"]
typos = ["runnig"]
with open("README.md", "r") as f:
readme = f.read()
self.assertTrue(readme, "README.md is empty")
... | |
https://github.com/teamqurrent/openai-python | The objective is to update the Audio API requests in the provided GitHub repository to include the fields api_version and organization. Additionally, update the version number in the `openai/version.py` file from 0.27.8 to 0.27.9. Add those fields in `openai/api_resources/audio.py` file, specifically in the `transcribe... | 041bf5a | requests >= 2.20
aiohttp
numpy
asyncio
matplotlib
plotly
pandas
scipy
scikit-learn
tenacity
typing-extensions
| python3.9 | d1c3658 | diff --git a/openai/api_resources/audio.py b/openai/api_resources/audio.py
--- a/openai/api_resources/audio.py
+++ b/openai/api_resources/audio.py
@@ -59,6 +59,8 @@ class Audio(APIResource):
api_key=api_key,
api_base=api_base,
api_type=api_type,
+ api_version=api_versio... | [
{
"content": "from typing import Any, List\n\nimport openai\nfrom openai import api_requestor, util\nfrom openai.api_resources.abstract import APIResource\n\n\nclass Audio(APIResource):\n OBJECT_NAME = \"audio\"\n\n @classmethod\n def _get_url(cls, action):\n return cls.class_url() + f\"/{action... | 2_0 | python | import sys
import unittest
import ast
import inspect
import textwrap
from typing import List, Union
class TestOpenAIFunctionsAndVersion(unittest.TestCase):
def test_openai_functions_and_version(self):
from openai.api_resources import Audio
from openai.version import VERSION
class FindPre... |
https://github.com/teamqurrent/openai-python | Handle timeout errors for asynchronous API requests in `openai/api_requestor.py` for `_interpret_async_response`. Add exception handling for aiohttp.ServerTimeoutError and asyncio.TimeoutError. When a timeout occurs, raise error.Timeout with the message "Request timed out" | 7610c5a | requests >= 2.20
aiohttp
numpy
asyncio
matplotlib
plotly
pandas
scipy
scikit-learn
tenacity
typing-extensions
| python3.9 | 041bf5a | diff --git a/openai/api_requestor.py b/openai/api_requestor.py
--- a/openai/api_requestor.py
+++ b/openai/api_requestor.py
@@ -720,6 +720,8 @@ class APIRequestor:
else:
try:
await result.read()
+ except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e:
+ ... | [
{
"content": "import asyncio\nimport json\nimport time\nimport platform\nimport sys\nimport threading\nimport time\nimport warnings\nfrom contextlib import asynccontextmanager\nfrom json import JSONDecodeError\nfrom typing import (\n AsyncGenerator,\n AsyncIterator,\n Callable,\n Dict,\n Iterator... | 2_1 | python | import sys
import unittest
import inspect
import textwrap
class TestAPIRequestorExceptions(unittest.TestCase):
def test_exceptions_in_api_requestor_code(self):
from openai.api_requestor import APIRequestor
source_code = inspect.getsource(APIRequestor._interpret_async_response)
source_cod... |
https://github.com/teamqurrent/openai-python | Remove unnecessary sorting by index in `openai/embeddings_utils.py` for both `get_embeddings` and `aget_embeddings` functions. | c975bce | requests >= 2.20
aiohttp
numpy
asyncio
matplotlib
plotly
pandas
scipy
scikit-learn
tenacity
typing-extensions
| python3.9 | f24d193 | diff --git a/openai/embeddings_utils.py b/openai/embeddings_utils.py
--- a/openai/embeddings_utils.py
+++ b/openai/embeddings_utils.py
@@ -46,7 +46,6 @@ def get_embeddings(
list_of_text = [text.replace("\n", " ") for text in list_of_text]
data = openai.Embedding.create(input=list_of_text, engine=engine, **k... | [
{
"content": "import textwrap as tr\nfrom typing import List, Optional\n\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nfrom scipy import spatial\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nfrom sklearn.metrics import average_precision_score, precision_recall_curve... | 2_2 | python | import sys
import unittest
import ast
import inspect
import textwrap
class TestSortedCallInFunctions(unittest.TestCase):
def test_sorted_call_in_functions(self):
from openai.embeddings_utils import aget_embeddings, get_embeddings
source_a = textwrap.dedent(inspect.getsource(get_embeddings))
... |
https://github.com/teamqurrent/openai-python | Change request logs in `openai/api_requestor.py` from info level to debug level. | 5d1a726 | requests >= 2.20
aiohttp
numpy
asyncio
matplotlib
plotly
pandas
scipy
scikit-learn
tenacity
typing-extensions
| python3.9 | e5b7d1a | diff --git a/openai/api_requestor.py b/openai/api_requestor.py
--- a/openai/api_requestor.py
+++ b/openai/api_requestor.py
@@ -490,7 +490,7 @@ class APIRequestor:
headers = self.request_headers(method, headers, request_id)
- util.log_info("Request to OpenAI API", method=method, path=abs_url)
+ ... | [
{
"content": "import asyncio\nimport json\nimport platform\nimport sys\nimport threading\nimport warnings\nfrom contextlib import asynccontextmanager\nfrom json import JSONDecodeError\nfrom typing import (\n AsyncGenerator,\n AsyncIterator,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\... | 2_3 | python | import sys
import unittest
import ast
import inspect
import textwrap
class TestLoggingCalls(unittest.TestCase):
def test_logging_calls(self):
from openai.api_requestor import APIRequestor
class FindPrepareRequest(ast.NodeVisitor):
exists: bool = False
debug_count: int = 0... |
https://github.com/teamqurrent/openai-python | Add optional api_key parameter to `Moderation.create` inside `openai/api_resources/moderation.py`. Be sure to add it to the instance init as a cls argument | e51ae91 | requests >= 2.20
aiohttp
numpy
asyncio
matplotlib
plotly
pandas
scipy
scikit-learn
tenacity
typing-extensions
| python3.9 | 09dc7ef | diff --git a/openai/api_resources/moderation.py b/openai/api_resources/moderation.py
--- a/openai/api_resources/moderation.py
+++ b/openai/api_resources/moderation.py
@@ -11,14 +11,14 @@ class Moderation(OpenAIObject):
return "/moderations"
@classmethod
- def create(cls, input: Union[str, List[str]],... | [
{
"content": "from typing import List, Optional, Union\n\nfrom openai.openai_object import OpenAIObject\n\n\nclass Moderation(OpenAIObject):\n VALID_MODEL_NAMES: List[str] = [\"text-moderation-stable\", \"text-moderation-latest\"]\n\n @classmethod\n def get_url(self):\n return \"/moderations\"\n... | 2_4 | python | import sys
import unittest
import ast
import inspect
import textwrap
from typing import List, Optional
class TestModerationMethod(unittest.TestCase):
def test_moderation_method(self):
from openai.api_resources.moderation import Moderation
class FindCls(ast.NodeVisitor):
args: Optiona... |
https://github.com/teamqurrent/openai-python | Inside `openai/api_resources/engine.py`, add an `embeddings` method. This method should take the params and return the embeddings from the OpenAI API | 205d063 | requests >= 2.20
aiohttp
numpy
asyncio
matplotlib
plotly
pandas
scipy
scikit-learn
tenacity
typing-extensions
| python3.9 | 7227906 | diff --git a/openai/api_resources/engine.py b/openai/api_resources/engine.py
--- a/openai/api_resources/engine.py
+++ b/openai/api_resources/engine.py
@@ -30,3 +30,6 @@ class Engine(ListableAPIResource, UpdateableAPIResource):
def search(self, **params):
return self.request("post", self.instance_url() +... | [
{
"content": "import time\n\nfrom openai import util\nfrom openai.api_resources.abstract import (\n ListableAPIResource,\n UpdateableAPIResource,\n)\nfrom openai.error import TryAgain\n\n\nclass Engine(ListableAPIResource, UpdateableAPIResource):\n OBJECT_NAME = \"engine\"\n\n def generate(self, tim... | 2_5 | python | import sys
import unittest
import ast
import inspect
class TestEngineEmbeddingsMethod(unittest.TestCase):
def has_method(self, class_obj, method_name):
source_lines = inspect.getsource(class_obj)
tree = ast.parse(source_lines)
for node in ast.walk(tree):
if isinstance(node, a... |
https://github.com/teamqurrent/storage-py | Add file_size_limit (int) and allow_mime_types ( attributes to the `BaseBucket` class inside `storage3/types.py` | ae9fc30 | typing-extensions == 4.2.0
httpx
python-dateutil == 2.8.2
toml
| python3.9 | 64e9e02 | diff --git a/storage3/types.py b/storage3/types.py
--- a/storage3/types.py
+++ b/storage3/types.py
@@ -18,6 +18,8 @@ class BaseBucket:
public: bool
created_at: datetime
updated_at: datetime
+ file_size_limit: int
+ allowed_mime_types: str
def __post_init__(self) -> None:
# created_a... | [
{
"content": "from dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import Optional, Union\n\nimport dateutil.parser\nfrom typing_extensions import Literal, TypedDict\n\nRequestMethod = Literal[\"GET\", \"POST\", \"DELETE\", \"PUT\", \"HEAD\"]\n\n\n@dataclass\nclass BaseBucket:\n \"\"... | 3_0 | python | import sys
import unittest
from dataclasses import fields
class TestBaseBucketClassVariables(unittest.TestCase):
def test_class_variables(self):
from storage3.types import BaseBucket
class_variables = [f.name for f in fields(BaseBucket)]
self.assertIn("file_size_limit", class_variables, ... |
https://github.com/teamqurrent/storage-py | Modify the way the StorageException is raised upon encountering an HTTPError during a request within the following files: `storage3/_async/bucket.py`, `storage3/_async/file_api.py`, `storage3/_sync/bucket.py`, and `storage3/_sync/file_api.py`. Please update these files individually. Instead of passing the response JSON... | 688cfc7 | typing-extensions == 4.2.0
httpx
python-dateutil == 2.8.2
toml
| python3.9 | 6923975 | diff --git a/storage3/_async/bucket.py b/storage3/_async/bucket.py
--- a/storage3/_async/bucket.py
+++ b/storage3/_async/bucket.py
@@ -31,7 +31,7 @@ class AsyncStorageBucketAPI:
try:
response.raise_for_status()
except HTTPError:
- raise StorageException(response.json())
+ ... | [
{
"content": "from __future__ import annotations\n\nfrom typing import Any, Optional\n\nfrom httpx import HTTPError, Response\n\nfrom ..types import RequestMethod\nfrom ..utils import AsyncClient, StorageException\nfrom .file_api import AsyncBucket\n\n__all__ = [\"AsyncStorageBucketAPI\"]\n\n\nclass AsyncStorag... | 3_1 | python | import sys
import unittest
import ast
import inspect
import textwrap
class TestStorageExceptionArgs(unittest.TestCase):
def check_method(self, method):
source = inspect.getsource(method)
source = textwrap.dedent(source)
# Check if "**" is present in the source
self.assertIn("**",... |
https://github.com/teamqurrent/storage-py | We need to rename storage to storage3. Follow the steps provided to achieve this. Change occurrences of 'storage' to 'storage3' in both the `pyproject.toml`'s name and version_files attributes. Update imports inside `storage/storage_client.py` to use storage module to storage3. Rename the directory storage to storage3. | d41b573 | typing-extensions == 4.2.0
httpx
python-dateutil == 2.8.2
toml
| python3.9 | c62151c | diff --git a/pyproject.toml b/pyproject.toml
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,5 +1,5 @@
[tool.poetry]
-name = "storage"
+name = "storage3"
version = "0.1.0"
description = "Supabase Storage client for Python."
authors = ["Joel Lee <joel@joellee.org>", "Leon Fedden <leonfedden@gmail.com>", "Daniel Rein... | [
{
"content": "[tool.poetry]\nname = \"storage\"\nversion = \"0.1.0\"\ndescription = \"Supabase Storage client for Python.\"\nauthors = [\"Joel Lee <joel@joellee.org>\", \"Leon Fedden <leonfedden@gmail.com>\", \"Daniel Reinón García <danielreinon@outlook.com>\", \"Leynier Gutiérrez González <leynier41@gmail.com>... | 3_2 | python | import sys
import unittest
import ast
import os
import toml
class TestSupabasePyRequirements(unittest.TestCase):
def get_imports(self, file_path):
with open(file_path, "r") as file:
tree = ast.parse(file.read())
imports = []
for node in ast.walk(tree):
if isinstan... |
https://github.com/teamqurrent/jquery | In git attributes, make sure that mjs and cjs files use UNIX line endings as well | 2b6b5e0 | python3.9 | 198b41c8 | diff --git a/.gitattributes b/.gitattributes
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,4 +2,7 @@
* text=auto
# JS files must always use LF for tools to work
+# JS files may have mjs or cjs extensions now as well
*.js eol=lf
+*.cjs eol=lf
+*.mjs eol=lf
| [
{
"content": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# JS files must always use LF for tools to work\n*.js eol=lf\n",
"path": ".gitattributes"
}
] | 4_0 | javascript | import sys
import unittest
class TestGitAttributes(unittest.TestCase):
def test_gitattributes_contents(self):
with open("./.gitattributes", "r") as f:
lines = f.readlines()
self.assertTrue(
("*.cjs eol=lf\n" in lines or "*.cjs text eol=lf\n" in lines) and
("*.mj... | |
https://github.com/teamqurrent/jquery | Modify the deprecated `.hover()` method in `src/deprecated/event.js` so that it does not rely on other deprecated methods: `.mouseenter()` & `.mouseleave()`. Use `.on()` instead. | 6616acf | python3.9 | fd6ffc5e | diff --git a/src/deprecated/event.js b/src/deprecated/event.js
--- a/src/deprecated/event.js
+++ b/src/deprecated/event.js
@@ -24,7 +24,9 @@ jQuery.fn.extend( {
},
hover: function( fnOver, fnOut ) {
- return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ return this
+ .on( "mouseenter", fnOver )
+... | [
{
"content": "import jQuery from \"../core.js\";\n\nimport \"../event.js\";\nimport \"../event/trigger.js\";\n\njQuery.fn.extend( {\n\n\tbind: function( types, data, fn ) {\n\t\treturn this.on( types, null, data, fn );\n\t},\n\tunbind: function( types, fn ) {\n\t\treturn this.off( types, null, fn );\n\t},\n\n\t... | 4_1 | javascript | import sys
import unittest
import subprocess
class TestEventJSContents(unittest.TestCase):
def test_event_js_contents(self):
with open("./src/deprecated/event.js", "r") as f:
content = f.read()
hover_start = content.find("hover: function(")
self.assertNotEqual(hover_sta... | |
https://github.com/teamqurrent/jquery | The `root` argument of `jQuery.fn.init` was needed to support `jQuery.sub`, but now this parameter is no longer needed. Remove it from the function arguments and only use rootjQuery instead. | 8cf39b7 | python3.9 | d2436df3 | diff --git a/src/core/init.js b/src/core/init.js
--- a/src/core/init.js
+++ b/src/core/init.js
@@ -15,7 +15,7 @@ var rootjQuery,
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
- init = jQuery.fn.init = function( selector, context, root ) {
+ init = jQuery.fn.init = funct... | [
{
"content": "// Initialize a jQuery object\nimport jQuery from \"../core.js\";\nimport document from \"../var/document.js\";\nimport rsingleTag from \"./var/rsingleTag.js\";\nimport isObviousHtml from \"./isObviousHtml.js\";\n\nimport \"../traversing/findFilter.js\";\n\n// A central reference to the root jQuer... | 4_2 | javascript | import sys
import unittest
import re
import subprocess
class TestInitJSContents(unittest.TestCase):
def test_init_js_contents(self):
with open("./src/core/init.js", "r") as f:
content = f.read()
pattern = r"jQuery\.fn\.init\s*=\s*function\s*\(([^)]+)\)"
match = re.search(patter... | |
https://github.com/teamqurrent/lodash | The `opt-cli` pre-push functionality was removed from lodash just a few days after it was added, but the documentation encouraging contributors to use it still remains. Remove the tips from the `CONTRIBUTING.md` file to avoid confusion for new contributors. | e002948 | python3.9 | 2f900b62f | diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -71,14 +71,3 @@ Guidelines are enforced using [ESLint](https://www.npmjs.com/package/eslint):
```bash
$ npm run style
```
-
-## Tips
-
-You can opt-in to a pre-push git hook by adding an `.op... | [
{
"content": "# :construction: Notice :construction:\n\nPardon the mess. The `master` branch is in flux while we work on Lodash v5. This\nmeans things like npm scripts, which we encourage using for contributions, may\nnot be working. Thank you for your patience.\n\n# Contributing to Lodash\n\nContributions are ... | 5_0 | javascript | import sys
import unittest
class TestContributingMDContents(unittest.TestCase):
def test_contributing_md_contents(self):
with open("./.github/CONTRIBUTING.md", "r") as f:
content = f.read()
self.assertNotIn("## Tips", content, "'## Tips' found in CONTRIBUTING.md")
self.assertNo... | |
https://github.com/teamqurrent/lodash | `nativeKeys.js` and `nativeKeysIn.js` each have their own functions: nativeKeys, and nativeKeysIn. Remove the files from the project. Search the repo and see if the functions are imported anywhere else. If they are, remove the imports and replace the functions with the code itself. | f3e0cbe | python3.9 | f7a6cddc9 | diff --git a/.internal/baseKeys.js b/.internal/baseKeys.js
--- a/.internal/baseKeys.js
+++ b/.internal/baseKeys.js
@@ -1,5 +1,4 @@
import isPrototype from './isPrototype.js'
-import nativeKeys from './nativeKeys.js'
/** Used to check objects for own properties. */
const hasOwnProperty = Object.prototype.hasOwnProp... | [
{
"content": "import isPrototype from './isPrototype.js'\nimport nativeKeys from './nativeKeys.js'\n\n/** Used to check objects for own properties. */\nconst hasOwnProperty = Object.prototype.hasOwnProperty\n\n/**\n * The base implementation of `keys` which doesn't treat sparse arrays as dense.\n *\n * @private... | 5_1 | javascript | import sys
import unittest
import os
import subprocess
class TestInternalJSFiles(unittest.TestCase):
def test_internal_js_files(self):
# Assert the absence of specific files
self.assertTrue(not os.path.isfile("./.internal/nativeKeys.js"), "File ./.internal/nativeKeys.js should not exist")
s... | |
https://github.com/teamqurrent/Python | Add a simple_moving_average.py calculation to the `financial` directory. The function should be named simple_moving_average and the args should be: data: Sequence[float], window_size: int. The function should return a list of floats. | 417b7ed | python3.10 | d051db1f | diff --git a/financial/simple_moving_average.py b/financial/simple_moving_average.py
new file mode 100644
--- /dev/null
+++ b/financial/simple_moving_average.py
@@ -0,0 +1,68 @@
+"""
+The Simple Moving Average (SMA) is a statistical calculation used to analyze data points
+by creating a constantly updated average price... | [] | 6_0 | python | import sys
import unittest
import os
import importlib.util
def run_function(file_path: str, function_name: str, function_args: list):
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Get the funct... | |
https://github.com/teamqurrent/Python | Modify the `searches/binary_search.py` file and add a function called exponential_search. The function args should be a list of ints which are some ascending sorted collection with comparable items, and an int which is the item value to search for. The function should return the index of the found item or -1 if not fou... | 06edc0e | python3.9 | b814cf37 | diff --git a/searches/binary_search.py b/searches/binary_search.py
--- a/searches/binary_search.py
+++ b/searches/binary_search.py
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
"""
-This is pure Python implementation of binary search algorithms
+Pure Python implementations of binary search algorithms
-For doctests run f... | [
{
"content": "#!/usr/bin/env python3\n\n\"\"\"\nThis is pure Python implementation of binary search algorithms\n\nFor doctests run following command:\npython3 -m doctest -v binary_search.py\n\nFor manual testing run:\npython3 binary_search.py\n\"\"\"\nfrom __future__ import annotations\n\nimport bisect\n\n\ndef... | 6_1 | python | import sys
import unittest
import os
import importlib.util
def run_function(file_path: str, function_name: str, function_args: list):
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Get the funct... | |
https://github.com/teamqurrent/Python | Create a vernam_cipher.py file in the `ciphers` directory with vernam_encrypt and vernam_decrypt functions. The function args should be a string which is the message to encrypt/decrypt, and a string which is the key. The function should return the encrypted/decrypted message. | be94690 | python3.9 | 34f48b68 | diff --git a/ciphers/vernam_cipher.py b/ciphers/vernam_cipher.py
new file mode 100644
--- /dev/null
+++ b/ciphers/vernam_cipher.py
@@ -0,0 +1,42 @@
+def vernam_encrypt(plaintext: str, key: str) -> str:
+ """
+ >>> vernam_encrypt("HELLO","KEY")
+ 'RIJVS'
+ """
+ ciphertext = ""
+ for i in range(len(pla... | [] | 6_2 | python | import sys
import unittest
import os
import importlib.util
def run_function(file_path: str, function_name: str, function_args: list):
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Get the funct... | |
https://github.com/teamqurrent/Python | Modify the `maths/volume.py` file and add a function for finding the volume of a icosahedron, call the function vol_icosahedron and it should take a single float argument which is the length of the side of the icosahedron. The function should return the volume of the icosahedron. | 1a26d76 | python3.9 | cc0405d0 | diff --git a/maths/volume.py b/maths/volume.py
--- a/maths/volume.py
+++ b/maths/volume.py
@@ -469,6 +469,35 @@ def vol_torus(torus_radius: float, tube_radius: float) -> float:
return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2)
+def vol_icosahedron(tri_side: float) -> float:
+ """Calculate the Volum... | [
{
"content": "\"\"\"\nFind the volume of various shapes.\n* https://en.wikipedia.org/wiki/Volume\n* https://en.wikipedia.org/wiki/Spherical_cap\n\"\"\"\nfrom __future__ import annotations\n\nfrom math import pi, pow\n\n\ndef vol_cube(side_length: float) -> float:\n \"\"\"\n Calculate the Volume of a Cube.... | 6_3 | python | import sys
import unittest
import importlib.util
def run_function(file_path: str, function_name: str, function_args: list):
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Get the function
f... | |
https://github.com/teamqurrent/Python | Add a new file to the `machine_learning/loss_functions` directory called huber_loss.py. The file should contain a function called huber_loss which takes three arguments, y_true y_pred, and delta. y_true and y_pred should be numpy arrays. The function should return the mean of huber loss. | 583a614 | numpy == 1.26.1 | python3.9 | 53d78b9c | diff --git a/machine_learning/loss_functions/huber_loss.py b/machine_learning/loss_functions/huber_loss.py
new file mode 100644
--- /dev/null
+++ b/machine_learning/loss_functions/huber_loss.py
@@ -0,0 +1,52 @@
+"""
+Huber Loss Function
+
+Description:
+Huber loss function describes the penalty incurred by an estimatio... | [] | 6_4 | python | import sys
import unittest
import numpy as np
import importlib.util
def run_function(file_path: str, function_name: str, function_args: list):
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Get ... |
https://github.com/teamqurrent/BitcoinPaperTrader | Add a method to the `Wallet` class in `trading_system.py` called profitFactor(). This method traverses the transactions list and will calculate the ratio of total profit made by all profitable trades divided by the total loss made by all unprofitable trades. | 388f8ce | numpy
datetime
pytz | python3.9 | dc3f4a0 | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -32,6 +32,70 @@ class Wallet:
self.short_stock = 0
self.transactions = []
+ def totalProfits(self, initial_wallet, final_wallet):
+ net = final_wallet - initial_wallet
+ percentage ... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_0 | python | import sys
import unittest
class TestSummary(unittest.TestCase):
def setUp(self):
from trading_system import Wallet
self.wallet = Wallet(50)
def test_profit_factor(self):
transactions = [
{'type': 'buy', 'price': 10, 'number': 5, 'timestamp': 1},
{'type'... |
https://github.com/teamqurrent/BitcoinPaperTrader | Implement a function in `trading_system.py` called user_settings(wallet, start_date, end_date, data_time_interval, historical_data), to change the historical data backtesting conditions and modify the data with user inputs like start date, end date, and time interval. Perform input validation on the user input to check... | 5e4d95a | numpy
datetime
pytz | python3.9 | b21e78b | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -1,14 +1,10 @@
import numpy as np
from datetime import datetime
+from datetime import timedelta
+import pytz
def load_historical_data(file_path):
- """
- Load and parse historical trading data from a file.... | [
{
"content": "import numpy as np\nfrom datetime import datetime\n\n\ndef load_historical_data(file_path):\n \"\"\"\n Load and parse historical trading data from a file.\n\n :param file_path: Path to the historical data file.\n :return: List of parsed data points.\n \"\"\"\n try:\n print... | 7_1 | python | import sys
import unittest
import pytz
from datetime import datetime
class TestUserSettings(unittest.TestCase):
@classmethod
def setUpClass(cls):
from trading_system import load_historical_data
# Load data once before running all test cases
cls.historical_data = load_historical_d... |
https://github.com/teamqurrent/BitcoinPaperTrader | Create a `Wallet` class inside `trading_system.py` that tracks balances of stock and cash, and has a list of the transactions made in the wallet. The init method should take in the initial wallet balance, then set the wallets balance, initial stock, and transaction list to be referenced later. Then add buy (buy(self, t... | 3ae437b | numpy
datetime
pytz | python3.9 | 95bba0b | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -3,6 +3,80 @@ from datetime import datetime
from datetime import timedelta
import pytz
+class Wallet:
+ def __init__(self, initial_cash):
+ self.cash = initial_cash
+ self.stock = 0
+ self.t... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\n\ndef load_historical_data(file_path):\n try:\n print(\"Loading Sim Data...\")\n with open(file_path) as f:\n lines = f.read().split(\"\\n\")\n lines = [line.spl... | 7_2 | python | import sys
import unittest
import math
class TestWallet(unittest.TestCase):
def setUp(self):
from trading_system import Wallet
self.wallet = Wallet(10000)
def test_initial_wallet_state(self):
self.assertEqual(self.wallet.cash, 10000)
self.assertEqual(self.wallet.stock,... |
https://github.com/teamqurrent/BitcoinPaperTrader | Add technical indicators class called TechnicalIndicators in `trading_system.py` with a heiken ashi method called heikin_ashi(data_point, previous_candle), that takes the previous and current OHLC candles (dicts with keys 'timestamp', 'open', 'high', 'low', 'close') and calculates the corresponding heiken ashi candle o... | 95bba0b | numpy
datetime
pytz | python3.9 | aa0dece | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -3,6 +3,28 @@ from datetime import datetime
from datetime import timedelta
import pytz
+class TechnicalIndicators:
+
+ # Method to create heiken ashi price candles
+ @staticmethod
+ def heikin_ashi(data_po... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass Wallet:\n def __init__(self, initial_cash):\n self.cash = initial_cash\n self.stock = 0\n self.transactions = []\n\n def buy(self, timestamp, price, number):\n\n ... | 7_3 | python | import sys
import unittest
def minute_to_ohlc(data, interval):
ohlc_data = []
for i in range(0, len(data), interval):
time_period = data[i:i + interval]
timestamps, prices = zip(*time_period)
ohlc = {}
ohlc['timestamp'] = timestamps[0]
ohlc['open'] = prices[0... |
https://github.com/teamqurrent/BitcoinPaperTrader | Implement a short method within the wallet class in `trading_system.py` that takes in the timestamp, price, and number to short, to allow algorithms to open short positions | aa0dece | numpy
datetime
pytz | python3.9 | eb5bb53 | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -29,6 +29,7 @@ class Wallet:
def __init__(self, initial_cash):
self.cash = initial_cash
self.stock = 0
+ self.short_stock = 0
self.transactions = []
def buy(self, timestamp... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_4 | python | import sys
import unittest
class TestShort(unittest.TestCase):
def setUp(self):
from trading_system import Wallet
self.wallet = Wallet(10000)
def test_short(self):
self.wallet.short(1, 1000, 1)
self.assertEqual(self.wallet.cash, 11000)
self.assertEqual(self.wal... |
https://github.com/teamqurrent/BitcoinPaperTrader | Implement a simple moving average algorithm class in `trading_system.py` that buys when the current price is below the moving average and sells then opens a short when its above the moving average. The class should have an init method that takes in a wallet (from the wallet class), the parsed and formatted price data, ... | eb5bb53 | numpy
datetime
pytz | python3.9 | 388f8ce | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -37,7 +37,7 @@ class Wallet:
print(f"Price: {price} is invalid")
return False
- if self.transactions and timestamp <= self.transactions[-1]['timestamp']:
+ if self.tran... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_5 | python | import sys
import unittest
class TestSMA(unittest.TestCase):
def setUp(self):
from trading_system import Wallet, SimpleMovingAverageStrategy
self.wallet = Wallet(1000)
self.data_points = [{'timestamp': 1, 'close': 2},
{'timestamp': 2, 'close': 3},
... |
https://github.com/teamqurrent/BitcoinPaperTrader | Add a method to the `Wallet` class in `trading_system.py` called totalProfits that takes in the initial wallet balance and the final wallet balance and returns the net profit as well as the profit percentage | 388f8ce | numpy
datetime
pytz | python3.9 | dc3f4a0 | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -32,6 +32,70 @@ class Wallet:
self.short_stock = 0
self.transactions = []
+ def totalProfits(self, initial_wallet, final_wallet):
+ net = final_wallet - initial_wallet
+ percentage ... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_6 | python | import sys
import unittest
class TestSummary(unittest.TestCase):
def setUp(self):
from trading_system import Wallet
self.wallet = Wallet(50)
def test_total_profits(self):
final_wallet = 100
expected_net = 50
expected_percentage = 100.0
net, percent... |
https://github.com/teamqurrent/BitcoinPaperTrader | Add method called exponential_moving_average to calculate exponential moving average to the `TechnicalIndicators` class in `trading_system.py`. It should take in OHLC data points and a window size and return the EMA at the most recent data point | dc3f4a0 | numpy
datetime
pytz | python3.9 | f856104 | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -23,6 +23,18 @@ class TechnicalIndicators:
new_candle['low'] = min(low, new_candle['open'], new_candle['close'])
return new_candle
+
+ # Method to calculate EMA (exponential moving average)
+... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_7 | python | import sys
import unittest
class TestEMA(unittest.TestCase):
def setUp(self):
self.data_points = [{'close': price} for price in [1, 2, 3, 4, 5]]
def test_exponential_moving_average(self):
from trading_system import TechnicalIndicators
# Manual EMA calculation based on dataset
... |
https://github.com/teamqurrent/BitcoinPaperTrader | Add a method to the `Wallet` class in `trading_system.py` called percentProfitable(), that calculates the number of profitable trades divided by total number of trades and returns this value as a floating point percentage (0-100). | 388f8ce | numpy
datetime
pytz | python3.9 | dc3f4a0 | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -32,6 +32,70 @@ class Wallet:
self.short_stock = 0
self.transactions = []
+ def totalProfits(self, initial_wallet, final_wallet):
+ net = final_wallet - initial_wallet
+ percentage ... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_8 | python | import sys
import unittest
class TestSummary(unittest.TestCase):
def setUp(self):
from trading_system import Wallet
self.wallet = Wallet(50)
def test_percent_profitable(self):
transactions = [
{'type': 'buy', 'price': 10, 'number': 5, 'timestamp': 1},
{... |
https://github.com/teamqurrent/BitcoinPaperTrader | Add a method to the `Wallet` class in `trading_system.py` called totalClosedTrades(), which calculates the total number of closed trades from the transactions list in the wallet. A closed trade can be considered when there is a sell operation for the purchased asset or a short operation closed. | 388f8ce | numpy
datetime
pytz | python3.9 | dc3f4a0 | diff --git a/trading_system.py b/trading_system.py
--- a/trading_system.py
+++ b/trading_system.py
@@ -32,6 +32,70 @@ class Wallet:
self.short_stock = 0
self.transactions = []
+ def totalProfits(self, initial_wallet, final_wallet):
+ net = final_wallet - initial_wallet
+ percentage ... | [
{
"content": "import numpy as np\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pytz\n\nclass TechnicalIndicators:\n\n # Method to create heiken ashi price candles\n @staticmethod\n def heikin_ashi(data_point, previous_candle):\n open_ = data_point['open']\n high =... | 7_9 | python | import sys
import unittest
class TestSummary(unittest.TestCase):
def setUp(self):
from trading_system import Wallet
self.wallet = Wallet(50)
def test_total_closed_trades(self):
transactions = [
{'type': 'buy', 'price': 10, 'number': 5, 'timestamp': 1},
... |
https://github.com/teamqurrent/web3.py | Resolve the issue of variable name collision in the Web3 Python library when initializing contracts. Specifically, fix the problem where a contract with a function named 'w3' causes a collision with the 'w3' instance variable in the contract classes. Modify the `contract.py` and `async_contract.py` files to handle the ... | 9c76a18 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 0302d372 | diff --git a/newsfragments/3147.bugfix.rst b/newsfragments/3147.bugfix.rst
new file mode 100644
--- /dev/null
+++ b/newsfragments/3147.bugfix.rst
@@ -0,0 +1 @@
+Fix collision of ``w3`` variable when initializing contract with function of the same name
\ No newline at end of file
diff --git a/tests/core/contracts/confte... | [
{
"content": "import functools\nimport pytest\n\nimport pytest_asyncio\n\nfrom tests.core.contracts.utils import (\n async_deploy,\n deploy,\n)\nfrom tests.utils import (\n async_partial,\n)\nfrom web3._utils.contract_sources.contract_data.arrays_contract import (\n ARRAYS_CONTRACT_DATA,\n)\nfrom we... | 8_0 | python | import sys
import unittest
class TestContractFunctionNameCollision(unittest.TestCase):
def setUp(self):
from web3 import Web3, EthereumTesterProvider
# Set up a Web3 instance with EthereumTesterProvider
self.w3 = Web3(EthereumTesterProvider())
self.contract_abi = [
... |
https://github.com/teamqurrent/web3.py | Update the `datastructures.py` file by implementing the `tupleize_lists_nested` function that is designed to convert lists to tuples in any mapping inputs, thereby making these objects hashable. In addition, modify the `__hash__` method in the `AttributeDict` class to apply this `tupleize_lists_nested` function before ... | 0c0e0de | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 1259fcfa | diff --git a/newsfragments/2908.bugfix.rst b/newsfragments/2908.bugfix.rst
new file mode 100644
--- /dev/null
+++ b/newsfragments/2908.bugfix.rst
@@ -0,0 +1 @@
+fix AttributeDicts unhashable if they contain lists recursively tupleizing them
diff --git a/tests/core/datastructures/test_tuplelize_nested_lists.py b/tests/c... | [
{
"content": "from collections import (\n OrderedDict,\n)\nfrom collections.abc import (\n Hashable,\n)\nfrom typing import (\n Any,\n Callable,\n Dict,\n Iterator,\n List,\n Mapping,\n MutableMapping,\n Optional,\n Sequence,\n Type,\n TypeVar,\n Union,\n cast,\n)\n\... | 8_1 | python | import sys
import unittest
import re
class TestTupleizationAndHashing(unittest.TestCase):
def setUp(self):
from web3.datastructures import (
AttributeDict
)
self.data = [
(
{
"mylst": [1, 2, 3, [4, 5, [6, 7], 8], 9, 10],
... |
https://github.com/teamqurrent/web3.py | Remove an unnecessary constant, `WHOLE_CONFUSABLES`, from the file `ens/_normalization.py`. This constant was not being used in the codebase, and its removal is part of code cleanup and optimization. | 32aca5a | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 1ff10a30 | diff --git a/ens/_normalization.py b/ens/_normalization.py
--- a/ens/_normalization.py
+++ b/ens/_normalization.py
@@ -215,7 +215,6 @@ def _construct_whole_confusable_map() -> Dict[int, Set[str]]:
WHOLE_CONFUSABLE_MAP = _construct_whole_confusable_map()
VALID_CODEPOINTS = _extract_valid_codepoints()
MAX_LEN_EMOJI_PA... | [
{
"content": "from enum import (\n Enum,\n)\nimport json\nimport os\nfrom sys import (\n version_info,\n)\nfrom typing import (\n Any,\n Dict,\n List,\n Optional,\n Set,\n Tuple,\n Union,\n)\n\nfrom pyunormalize import (\n NFC,\n NFD,\n)\n\nfrom .exceptions import (\n Invalid... | 8_10 | python | import unittest
import sys
class TestNormalizationConstantRemoval(unittest.TestCase):
def test_whole_confusables_removal(self):
from ens import _normalization
# test if the constant has been removed
self.assertFalse(hasattr(_normalization, 'WHOLE_CONFUSABLES'), "WHOLE_CONFUSABLES shoul... |
https://github.com/teamqurrent/web3.py | Prevent circular import by moving around the import order in `web3/providers/__init__.py`. You should move the .persistent import to be below the websocket import | 33d186b | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | a17ff88f | diff --git a/web3/providers/__init__.py b/web3/providers/__init__.py
--- a/web3/providers/__init__.py
+++ b/web3/providers/__init__.py
@@ -11,9 +11,6 @@ from .base import (
from .ipc import (
IPCProvider,
)
-from .persistent import (
- PersistentConnectionProvider,
-)
from .rpc import (
HTTPProvider,
)... | [
{
"content": "from .async_base import (\n AsyncBaseProvider,\n)\nfrom .async_rpc import (\n AsyncHTTPProvider,\n)\nfrom .base import (\n BaseProvider,\n JSONBaseProvider,\n)\nfrom .ipc import (\n IPCProvider,\n)\nfrom .persistent import (\n PersistentConnectionProvider,\n)\nfrom .rpc import (\... | 8_11 | python | import unittest
class TestUtilityMethods(unittest.TestCase):
def test_either_set_is_a_subset_with_percentage(self):
import web3._utils.utility_methods as utility_methods
set_a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
set_b = {1, 2, 3, 4, 5, 6, 7, 8, 9}
# 90% of set_a is in set_b... |
https://github.com/teamqurrent/web3.py | Improve the caching mechanism for responses in the `WebsocketProviderV2` class. This includes ensuring that all undesired responses are cached correctly and that a cached response is returned immediately without needing to call recv() again. Implement a timeout mechanism for the make_request method in the `WebsocketPro... | ef022ef | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | f55177b3 | diff --git a/tests/core/providers/test_wsv2_provider.py b/tests/core/providers/test_wsv2_provider.py
--- a/tests/core/providers/test_wsv2_provider.py
+++ b/tests/core/providers/test_wsv2_provider.py
@@ -6,6 +6,9 @@ from eth_utils import (
to_bytes,
)
+from web3.exceptions import (
+ TimeExhausted,
+)
from w... | [
{
"content": "import json\nimport pytest\nimport sys\n\nfrom eth_utils import (\n to_bytes,\n)\n\nfrom web3.providers.websocket import (\n WebsocketProviderV2,\n)\nfrom web3.types import (\n RPCEndpoint,\n)\n\n\n@pytest.mark.asyncio\n@pytest.mark.skipif(\n # TODO: remove when python 3.7 is no longer... | 8_12 | python | import asyncio
import sys
import pytest
def _mock_ws(provider):
from unittest.mock import AsyncMock
provider._ws = AsyncMock()
@pytest.mark.asyncio
@pytest.mark.skipif(
sys.version_info < (3, 8),
reason="Uses AsyncMock, not supported by python 3.7",
)
async def test_async_make_request_times_out_of_w... |
https://github.com/teamqurrent/web3.py | Modify the `disconnect` method of `WebSocketProviderV2` so that it no longer writes to the log when catching the exception. | fe96e1e | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 9ae0e13 | diff --git a/web3/providers/websocket/websocket_v2.py b/web3/providers/websocket/websocket_v2.py
--- a/web3/providers/websocket/websocket_v2.py
+++ b/web3/providers/websocket/websocket_v2.py
@@ -154,12 +154,8 @@ class WebsocketProviderV2(PersistentConnectionProvider):
try:
self._message_listener_t... | [
{
"content": "import asyncio\nimport json\nimport logging\nimport os\nfrom typing import (\n Any,\n Dict,\n Optional,\n Union,\n)\n\nfrom eth_typing import (\n URI,\n)\nfrom toolz import (\n merge,\n)\nfrom websockets.client import (\n connect,\n)\nfrom websockets.exceptions import (\n W... | 8_13 | python | import sys
from _ast import AsyncFunctionDef
import inspect
import ast
from typing import Any
class DisconnectAnalyzer(ast.NodeVisitor):
def __init__(self):
self.has_pass = False
self.has_logger_info = False
def visit_Pass(self, node):
self.has_pass = True
def visit_Attribute(s... |
https://github.com/teamqurrent/web3.py | The pluggy dependency is no longer needed. Remove pluggy from `setup.py` and verify it is no longer there. | be76120 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 4ee4c865 | diff --git a/newsfragments/2992.internal.rst b/newsfragments/2992.internal.rst
new file mode 100644
--- /dev/null
+++ b/newsfragments/2992.internal.rst
@@ -0,0 +1 @@
+Removed `pluggy` from dev requirements
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -37,7 +37,6 @@ extras_require = {
"tox>... | [
{
"content": "#!/usr/bin/env python\nfrom setuptools import (\n find_packages,\n setup,\n)\n\nextras_require = {\n \"tester\": [\n \"eth-tester[py-evm]==v0.9.0-b.1\",\n \"py-geth>=3.11.0\",\n ],\n \"linter\": [\n \"black>=22.1.0\",\n \"flake8==3.8.3\",\n \"isort... | 8_2 | python | import unittest
import sys
class TestSetupPy(unittest.TestCase):
def test_pluggy_not_in_setup_py(self):
with open('setup.py', 'r') as file:
setup_py_contents = file.read()
self.assertNotIn('pluggy', setup_py_contents)
def main():
suite = unittest.TestSuite()
suite.addTe... |
https://github.com/teamqurrent/web3.py | The middlewares `request_parameter_normalizer` and `pythonic` should no longer be included in the default stack. Remove them from being returned in `manager.py` | 674e342 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 070e2288 | diff --git a/tests/core/manager/test_default_middlewares.py b/tests/core/manager/test_default_middlewares.py
--- a/tests/core/manager/test_default_middlewares.py
+++ b/tests/core/manager/test_default_middlewares.py
@@ -11,19 +11,15 @@ from web3.middleware import (
buffered_gas_estimate_middleware,
gas_price_s... | [
{
"content": "from web3.manager import (\n RequestManager,\n)\nfrom web3.middleware import (\n abi_middleware,\n async_attrdict_middleware,\n async_buffered_gas_estimate_middleware,\n async_gas_price_strategy_middleware,\n async_validation_middleware,\n attrdict_middleware,\n buffered_ga... | 8_3 | python | import unittest
import sys
class TestMiddlewareRemoval(unittest.TestCase):
def test_removed_middlewares_not_in_default_stack(self):
from web3 import Web3
from web3.middleware import (
pythonic_middleware,
request_parameter_normalizer,
)
w3 = Web3()
... |
https://github.com/teamqurrent/web3.py | Enhance the robustness of the formatting middleware in the web3.py library by ensuring it correctly handles cases where the response result is None in `formatting.py`. This change prevents potential errors or unexpected behaviors when the middleware encounters None values in the response. | 0a1da2d | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 12f3702 | diff --git a/newsfragments/2546.bugfix.rst b/newsfragments/2546.bugfix.rst
new file mode 100644
--- /dev/null
+++ b/newsfragments/2546.bugfix.rst
@@ -0,0 +1 @@
+Handle `None` in the formatting middleware
\ No newline at end of file
diff --git a/tests/core/middleware/test_formatting_middleware.py b/tests/core/middleware... | [
{
"content": "from typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Coroutine,\n Optional,\n)\n\nfrom eth_utils.toolz import (\n assoc,\n merge,\n)\n\nfrom web3.types import (\n AsyncMiddleware,\n AsyncMiddlewareCoroutine,\n Formatters,\n FormattersDict,\n Literal,\n ... | 8_4 | python | import unittest
import sys
class TestFormattingMiddleware(unittest.TestCase):
def test_formatting_middleware_handles_none(self):
from web3 import Web3
from web3.middleware import construct_formatting_middleware, construct_result_generator_middleware
from web3.types import RPCEndpoint
... |
https://github.com/teamqurrent/web3.py | Ensure that the time-based gas price strategy correctly returns the default gas price in scenarios where the blockchain has no transactions to sample from by modifying the function `time_based_gas_price_strategy` in `time_based.py` and adding a condition to return w3.eth.gas_price when the latest block number is 0, ind... | 66f2391 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 5dca5243 | diff --git a/newsfragments/1149.bugfix.rst b/newsfragments/1149.bugfix.rst
new file mode 100644
--- /dev/null
+++ b/newsfragments/1149.bugfix.rst
@@ -0,0 +1 @@
+Return `w3.eth.gas_price` when calculating time based gas price strategy for an empty chain.
\ No newline at end of file
diff --git a/tests/core/gas-strategies... | [
{
"content": "import pytest\n\nfrom web3 import (\n Web3,\n constants,\n)\nfrom web3.exceptions import (\n Web3ValidationError,\n)\nfrom web3.gas_strategies.time_based import (\n construct_time_based_gas_price_strategy,\n)\nfrom web3.middleware import (\n construct_result_generator_middleware,\n)... | 8_5 | python | import unittest
import sys
class TestTimeBasedGasPriceStrategy(unittest.TestCase):
def _get_initial_block(self, method, params):
return {
"hash": "0x" + "00" * 32,
"number": 0,
"parentHash": None,
"transactions": [],
"miner": "0x" + "Aa" * 20,
... |
https://github.com/teamqurrent/web3.py | You need to clean up the code in the `web3/_utils/async_transactions.py` file. This involves removing a specific function and its related dependencies that are no longer needed. The function in question is `async_handle_offchain_lookup`, which handles offchain lookups in transactions. This function, along with its asso... | e48a480 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 63b85fa9 | diff --git a/web3/_utils/async_transactions.py b/web3/_utils/async_transactions.py
--- a/web3/_utils/async_transactions.py
+++ b/web3/_utils/async_transactions.py
@@ -1,16 +1,10 @@
from typing import (
TYPE_CHECKING,
- Any,
- Dict,
Optional,
cast,
)
-from eth_abi import (
- abi,
-)
from eth... | [
{
"content": "from typing import (\n TYPE_CHECKING,\n Any,\n Dict,\n Optional,\n cast,\n)\n\nfrom eth_abi import (\n abi,\n)\nfrom eth_typing import (\n URI,\n ChecksumAddress,\n)\nfrom eth_utils.toolz import (\n assoc,\n merge,\n)\nfrom hexbytes import (\n HexBytes,\n)\n\nfrom ... | 8_6 | python | import unittest
import sys
class TestAsyncTransactionsRemoval(unittest.TestCase):
def test_offchain_lookup_method_removed(self):
from web3._utils import async_transactions
# Test will pass if the 'async_handle_offchain_lookup' method is not present
self.assertFalse(hasattr(async_transact... |
https://github.com/teamqurrent/web3.py | Make the `_PersistentConnectionWeb3` class awaitable. The asynchronous operation should connect to the provider if the provider's `_ws` attribute is None. | 1249144 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 66ca261 | diff --git a/web3/main.py b/web3/main.py
--- a/web3/main.py
+++ b/web3/main.py
@@ -35,6 +35,7 @@ from typing import (
Any,
AsyncIterator,
Dict,
+ Generator,
List,
Optional,
Sequence,
@@ -130,7 +131,9 @@ from web3.providers.rpc import (
from web3.providers.websocket import (
Websoc... | [
{
"content": "import decimal\nimport warnings\nfrom types import (\n TracebackType,\n)\n\nfrom ens import (\n AsyncENS,\n ENS,\n)\nfrom eth_abi.codec import (\n ABICodec,\n)\nfrom eth_utils import (\n add_0x_prefix,\n apply_to_return_value,\n from_wei,\n is_address,\n is_checksum_addr... | 8_7 | python | import pytest
from unittest.mock import (
AsyncMock,
Mock,
patch,
)
from web3 import (
AsyncWeb3,
)
from web3.providers.websocket import (
WebsocketProviderV2,
)
from web3.types import (
RPCEndpoint,
)
import sys
def _mock_ws(provider):
provider._ws = AsyncMock()
async def _coro():
r... |
https://github.com/teamqurrent/web3.py | The objective of the commit is to enhance the efficiency and responsiveness of the event loop in the web3.py project by implementing several key changes across different files. Firstly, use asyncio.sleep(0) is as an efficient way to yield control back to the event loop, allowing it to manage multiple tasks concurrently... | 2db5fee | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | 2c78c125 | diff --git a/tests/core/providers/test_wsv2_provider.py b/tests/core/providers/test_wsv2_provider.py
--- a/tests/core/providers/test_wsv2_provider.py
+++ b/tests/core/providers/test_wsv2_provider.py
@@ -1,3 +1,4 @@
+import asyncio
import json
import pytest
import sys
@@ -87,7 +88,7 @@ async def test_async_make_reque... | [
{
"content": "import json\nimport pytest\nimport sys\n\nfrom eth_utils import (\n to_bytes,\n)\n\nfrom web3.exceptions import (\n TimeExhausted,\n)\nfrom web3.providers.websocket import (\n WebsocketProviderV2,\n)\nfrom web3.types import (\n RPCEndpoint,\n)\n\n\ndef _mock_ws(provider):\n # move t... | 8_8 | python | import unittest
import asyncio
import sys
class TestWebsocketProviderV2(unittest.TestCase):
def test_default_timeout_increased(self):
from web3.providers.websocket import WebsocketProviderV2
# Test that the default timeout for awaiting responses is now 50 seconds.
provider = WebsocketPro... |
https://github.com/teamqurrent/web3.py | Enhance the accuracy of empty string checks in the `ens/utils.py` file. Specifically strip the input string before checking if it's empty to accurately catch cases where the input might contain only blank spaces, which should still be considered as an empty name. | 12f3702 | -e . [tester]
idna
pytest
pytest_asyncio
eth-tester[py-evm]==v0.9.1-b.1
py-geth>=3.11.0 | python3.9 | b5e302a7 | diff --git a/ens/utils.py b/ens/utils.py
--- a/ens/utils.py
+++ b/ens/utils.py
@@ -127,10 +127,12 @@ def normalize_name(name: str) -> str:
elif isinstance(name, (bytes, bytearray)):
name = name.decode("utf-8")
+ clean_name = name.strip()
+
try:
- return idna.uts46_remap(name, std3_rules=T... | [
{
"content": "from datetime import (\n datetime,\n timezone,\n)\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Collection,\n Dict,\n List,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n cast,\n)\n\nfrom eth_typing import (\n Address,\n ChecksumAd... | 8_9 | python | import unittest
import sys
class TestEnsEncodeName(unittest.TestCase):
def test_ens_encode_name_empty(self):
from ens.utils import ens_encode_name
# Test for the none and empt name types
for empty_name in ("", ".", None, " ", " "):
with self.subTest(empty_name=empty_name):
... |
https://github.com/teamqurrent/pypush | Enhance the handling of incoming messages in the pypush repository by introducing a thread-safe queue mechanism. To do this, modify the `apns.py` file to replace the existing list-based message storage with a new class called IncomingQueue that ensures thread safety. Focus on implementing synchronized methods for addin... | 27528bf | requests
cryptography
wheel
tlslite-ng==0.8.0a43
srp
pbkdf2 | python3.9 | b3ead0c | diff --git a/apns.py b/apns.py
--- a/apns.py
+++ b/apns.py
@@ -29,13 +29,53 @@ def _connect(private_key: str, cert: str) -> tlslite.TLSConnection:
return sock
+class IncomingQueue:
+ def __init__(self):
+ self.queue = []
+ self.lock = threading.Lock()
+
+ def append(self, item):
+ ... | [
{
"content": "from __future__ import annotations\n\nimport random\nimport socket\nimport threading\nimport time\nfrom hashlib import sha1\n\nimport tlslite\n\nimport albert\n\nCOURIER_HOST = \"windows.courier.push.apple.com\" # TODO: Get this from config\nCOURIER_PORT = 5223\nALPN = [b\"apns-security-v2\"]\n\n... | 9_0 | python | import unittest
import threading
import sys
class TestIncomingQueue(unittest.TestCase):
def test_thread_safety(self):
from apns import IncomingQueue
queue = IncomingQueue()
items_to_add = 100
def add_items():
for _ in range(items_to_add):
que... |
https://github.com/teamqurrent/pypush | To enhance the project's command-line interface capabilities, you need to add the prompt_toolkit library to the project's dependencies. This involves modifying the `requirements.txt` file to include this new dependency. | 3ef1b6e | requests
cryptography
wheel
tlslite-ng==0.8.0a43
srp
pbkdf2 | python3.9 | db90bf5 | diff --git a/requirements.txt b/requirements.txt
--- a/requirements.txt
+++ b/requirements.txt
@@ -5,4 +5,5 @@ tlslite-ng==0.8.0a43
srp
pbkdf2
unicorn
-rich
\ No newline at end of file
+rich
+prompt_toolkit
\ No newline at end of file
| [
{
"content": "requests\ncryptography\nwheel\ntlslite-ng==0.8.0a43\nsrp\npbkdf2\nunicorn\nrich",
"path": "requirements.txt"
}
] | 9_1 | python | import unittest
import os
import sys
class TestRequirementsFile(unittest.TestCase):
def test_prompt_toolkit_in_requirements(self):
# Path to the requirements.txt file
requirements_path = os.path.join(os.path.dirname(__file__), 'requirements.txt')
with open(requirements_path, 'r') as file... |
https://github.com/teamqurrent/pypush | Enhance the flexibility in specifying the sender of an iMessage. Modify the `from_raw` method in the `imessage.py` file to accept an additional optional parameter for the sender. Adjust the logic within this method to prioritize this new parameter over the last participant in the message for determining the sender. | be9a278 | requests
cryptography
wheel
tlslite-ng==0.8.0a43
srp
pbkdf2 | python3.10 | 74fff8b | diff --git a/imessage.py b/imessage.py
--- a/imessage.py
+++ b/imessage.py
@@ -85,7 +85,7 @@ class iMessage:
return True
- def from_raw(message: bytes) -> "iMessage":
+ def from_raw(message: bytes, sender: str | None = None) -> "iMessage":
"""Create an `iMessage` from raw message bytes"""
... | [
{
"content": "# LOW LEVEL imessage function, decryption etc\n# Don't handle APNS etc, accept it already setup\n\n## HAVE ANOTHER FILE TO SETUP EVERYTHING AUTOMATICALLY, etc\n# JSON parsing of keys, don't pass around strs??\n\nimport gzip\nimport logging\nimport plistlib\nimport random\nimport uuid\nfrom datacla... | 9_2 | python | import unittest
import plistlib
import sys
class TestIMessageFromRaw(unittest.TestCase):
def test_from_raw_with_explicit_sender(self):
from imessage import iMessage
# Create a dummy message dictionary that would represent the parsed message bytes
dummy_message = {
"t": "Test... |
https://github.com/teamqurrent/pypush | The goal is to streamline the authentication process in our project by removing `gsa.py` as it was only added for testing. We need to remove the dependency on `gsa.py` and its associated GrandSlam authentication method, particularly in `ids/profile.py`. Focus on simplifying the `get_auth_token` function by eliminating ... | 213f90a | requests
cryptography
wheel
tlslite-ng==0.8.0a43
srp
pbkdf2 | python3.10 | d740f3b | diff --git a/gsa.py b/gsa.py
deleted file mode 100644
--- a/gsa.py
+++ /dev/null
@@ -1,535 +0,0 @@
-import getpass
-import hashlib
-import hmac
-import json
-import locale
-import plistlib as plist
-import uuid
-from base64 import b64decode, b64encode
-from datetime import datetime
-from random import randbytes
-
-impo... | [
{
"content": "import getpass\nimport hashlib\nimport hmac\nimport json\nimport locale\nimport plistlib as plist\nimport uuid\nfrom base64 import b64decode, b64encode\nfrom datetime import datetime\nfrom random import randbytes\n\nimport pbkdf2\nimport requests\nimport srp._pysrp as srp\nfrom cryptography.hazmat... | 9_3 | python | import unittest
import sys
import inspect
class TestCommitChanges(unittest.TestCase):
def test_gsa_removal(self):
with self.assertRaises(ImportError):
import gsa
def test_gsa_import_removal_in_profile(self):
from ids import profile
# This checks if 'gsa' is not in the gl... |
https://github.com/teamqurrent/pypush | Cleanup the repository by removing `data.plist` from the `emulated` folder | c87d188 | requests
cryptography
wheel
tlslite-ng==0.8.0a43
srp
pbkdf2 | python3.9 | 4939ea0 | diff --git a/emulated/data.plist b/emulated/data.plist
deleted file mode 100644
--- a/emulated/data.plist
+++ /dev/null
@@ -1,55 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <ke... | [
{
"content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>iokit</key>\n <dict>\n <key>4D1EDE05-38C7-4A6A-9CC6-4BCCA8B38C14:MLB</key>\n <data>\n ... | 9_4 | python | import unittest
import sys
import os
class TestDataPlistRemoval(unittest.TestCase):
def test_data_plist_removal(self):
# Check that 'emulated/data.plist' does not exist
self.assertFalse(os.path.exists('emulated/data.plist'))
def main():
suite = unittest.TestSuite()
suite.addTests(unitte... |
https://github.com/teamqurrent/pypush | In the file `imessage.py` participants should be case insensitive when reading the user cache. Add a line to turn participants to lower case before checking for push tokens | 627cedf | requests
cryptography
wheel
tlslite-ng==0.8.0a43
srp
pbkdf2 | python3.9 | e2102d0 | diff --git a/imessage.py b/imessage.py
--- a/imessage.py
+++ b/imessage.py
@@ -496,6 +496,7 @@ class iMessageUser:
bundled_payloads = []
for participant in message.participants:
+ participant = participant.lower()
for push_token in self.USER_CACHE[participant]:
... | [
{
"content": "# LOW LEVEL imessage function, decryption etc\n# Don't handle APNS etc, accept it already setup\n\n## HAVE ANOTHER FILE TO SETUP EVERYTHING AUTOMATICALLY, etc\n# JSON parsing of keys, don't pass around strs??\n\nimport base64\nimport gzip\nimport logging\nimport plistlib\nimport random\nfrom typin... | 9_5 | python | import unittest
import sys
class TestCodeStructure(unittest.TestCase):
def test_participant_lowercasing_in_send_method(self):
with open('imessage.py', 'r') as file:
lines = file.readlines()
expected_line = " participant = participant.lower()\n"
preceding_line = " ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.