internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: abey79/vpype

Issue:
`write_svg()` must set `stroke-opacity` instead of using RGBA
Inkscape doesn't support RGBA


Discussion:

Resolving patch:
diff --git a/vpype/io.py b/vpype/io.py
--- a/vpype/io.py
+++ b/vpype/io.py
@@ -748,21 +748,24 @@ def write_svg(
         group = inkscape.layer(label=label)
         group.attribs["fill"] = "none"
 
+        color = Color("black")
         if color_mode == "layer" or (
             color_mode == "default" and not layer.property_exists(METADATA_FIELD_COLOR)
         ):
-            group.attribs["stroke"] = METADATA_DEFAULT_COLOR_SCHEME[
+            color = METADATA_DEFAULT_COLOR_SCHEME[
                 color_idx % len(METADATA_DEFAULT_COLOR_SCHEME)
             ]
             color_idx += 1
         elif color_mode == "default":
-            group.attribs["stroke"] = str(layer.property(METADATA_FIELD_COLOR))
+            color = Color(layer.property(METADATA_FIELD_COLOR))
 
             # we want to avoid a subsequent layer whose color is undefined to have its color
             # affected by whether or not previous layer have their color defined
             color_idx += 1
-        elif color_mode == "none":
-            group.attribs["stroke"] = "black"
+
+        group.attribs["stroke"] = color.as_rgb_hes()
+        if color.alpha < 255:
+            group.attribs["stroke-opacity"] = f"{color.alpha/255:.3f}"
         group.attribs["style"] = "display:inline"
         group.attribs["id"] = f"layer{layer_id}"
         if layer.property_exists(METADATA_FIELD_PEN_WIDTH):
diff --git a/vpype/metadata.py b/vpype/metadata.py
--- a/vpype/metadata.py
+++ b/vpype/metadata.py
@@ -60,6 +60,10 @@ def as_hex(self) -> str:
         """Return a standard, hexadecimal representation of the instance."""
         return svgelements.Color(self.red, self.green, self.blue, self.alpha).hex
 
+    def as_rgb_hes(self) -> str:
+        """Return a standard, hexadecimal representation of the instance, ignoring alpha."""
+        return svgelements.Color(self.red, self.green, self.blue).hexrgb
+
     def __str__(self) -> str:
         return self.as_hex()
 


Test patch:
diff --git a/tests/test_files.py b/tests/test_files.py
--- a/tests/test_files.py
+++ b/tests/test_files.py
@@ -428,6 +428,18 @@ def test_write_svg_svg_props_unknown_namespace(capsys):
     assert 'unknown:version="1.1.0"' not in capsys.readouterr().out
 
 
+def test_write_opacity_100pct(capsys):
+    vpype_cli.execute("line 0 0 10 10 color red write -f svg -")
+    assert 'stroke="#ff0000"' in capsys.readouterr().out
+
+
+def test_write_opacity_50pct(capsys):
+    vpype_cli.execute("line 0 0 10 10 color '#ff00007f' write -f svg -")
+    output = capsys.readouterr().out
+    assert 'stroke="#ff0000"' in output
+    assert 'stroke-opacity="0.498"' in output
+
+
 def test_read_no_fail():
     with pytest.raises(click.BadParameter):
         vpype_cli.execute("read doesnotexist.svg")
Repository: abey79/vpype

Issue:
Replace cKDTree by KDTree
see note here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy.spatial.cKDTree


Discussion:

Resolving patch:
diff --git a/vpype/line_index.py b/vpype/line_index.py
--- a/vpype/line_index.py
+++ b/vpype/line_index.py
@@ -4,14 +4,14 @@
 from typing import Iterable
 
 import numpy as np
-from scipy.spatial import cKDTree as KDTree
+from scipy.spatial import KDTree
 
 # REMINDER: anything added here must be added to docs/api.rst
 __all__ = ["LineIndex"]
 
 
 class LineIndex:
-    """Wrapper to scipy.spatial.cKDTree to facilitate systematic processing of a line
+    """Wrapper to scipy.spatial.KDTree to facilitate systematic processing of a line
     collection.
 
     Implementation note: we use the `available` bool array because deleting stuff from the


Test patch:
Repository: abey79/vpype

Issue:
viewer: the document is not refitted when changed with "fit to view" activated
This affects vsketch, when document size is updated by parameters.


Discussion:

Resolving patch:
diff --git a/vpype_viewer/engine.py b/vpype_viewer/engine.py
--- a/vpype_viewer/engine.py
+++ b/vpype_viewer/engine.py
@@ -126,6 +126,11 @@ def document(self) -> vp.Document | None:
     def document(self, document: vp.Document | None) -> None:
         self._document = document
         self._layer_visibility.clear()
+
+        # keep fitted to the viewport
+        if self._fit_to_viewport_flag:
+            self.fit_to_viewport()
+
         self._update()
 
     @property


Test patch:
Repository: abey79/vpype

Issue:
Default to QT_QPA_PLATFORM=xcb on Linux/Wayland
If we detect a linux box running on wayland, we should force Qt to use the xcb platform as the wayland backend doesn't work properly with moderngl.

This maybe a good way to detect wayland:
```
XDG_SESSION_TYPE=wayland
```

Relevant discussions:
- https://github.com/abey79/vsketch/issues/353
- https://discord.com/channels/550302843777712148/696045774970028062/1072436292798926868


Discussion:
Also, #584 

Resolving patch:
diff --git a/vpype_viewer/qtviewer/__init__.py b/vpype_viewer/qtviewer/__init__.py
--- a/vpype_viewer/qtviewer/__init__.py
+++ b/vpype_viewer/qtviewer/__init__.py
@@ -1 +1,18 @@
+def _check_wayland():
+    """Fix QT env variable on Wayland-based systems.
+
+    See https://github.com/abey79/vpype/issues/596
+    """
+    import os
+    import sys
+
+    if sys.platform.startswith("linux"):
+        if os.environ.get("XDG_SESSION_TYPE", "") == "wayland":
+            if "QT_QPA_PLATFORM" not in os.environ:
+                os.environ["QT_QPA_PLATFORM"] = "xcb"
+
+
+_check_wayland()
+
+
 from .viewer import *


Test patch:
Repository: abey79/vpype

Issue:
Examples in `lreverse`'help are wrong
As title says ☝🏻 


Discussion:

Resolving patch:
diff --git a/vpype_cli/layerops.py b/vpype_cli/layerops.py
--- a/vpype_cli/layerops.py
+++ b/vpype_cli/layerops.py
@@ -269,17 +269,9 @@ def lreverse(document: vp.Document, layers) -> vp.Document:
     (to refer to every exising layers).
 
     Examples:
-        Delete layer one:
+        Reverse path order in layer 1:
 
-            $ vpype [...] ldelete 1 [...]
-
-        Delete layers 1 and 2:
-
-            $ vpype [...] ldelete 1,2 [...]
-
-        Delete all layers:
-
-            $ vpype [...] ldelete all [...]
+            $ vpype [...] lreverse 1 [...]
     """
 
     lids = set(multiple_to_layer_ids(layers, document))


Test patch:
Repository: jumpserver/jumpserver

Issue:
已有的系统用户不用修改密码
现象：
      现在这个版本的jumpserver  为什么我在推送一个操作系统中已经存在的账户（比如叫oracle），会自动修改oracle用户的密码，我明明只选择了 “使用密钥



Discussion:

Resolving patch:
diff --git a/jperm/perm_api.py b/jperm/perm_api.py
--- a/jperm/perm_api.py
+++ b/jperm/perm_api.py
@@ -182,8 +182,9 @@ def gen_resource(ob, perm=None):
                 info = {'hostname': asset.hostname,
                         'ip': asset.ip,
                         'port': asset_info.get('port', 22),
+                        'ansible_ssh_private_key_file': role_key,
                         'username': role.name,
-                        'password': CRYPTOR.decrypt(role.password)
+                        # 'password': CRYPTOR.decrypt(role.password)
                        }
 
                 if os.path.isfile(role_key):
diff --git a/jperm/views.py b/jperm/views.py
--- a/jperm/views.py
+++ b/jperm/views.py
@@ -519,12 +519,12 @@ def perm_role_push(request):
             ret["pass_push"] = task.add_user(role.name)
             ret["key_push"] = task.push_key(role.name, os.path.join(role.key_path, 'id_rsa.pub'))
 
-        # 2. 推送账号密码
-        elif password_push:
-            ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password))
+        # 2. 推送账号密码 <为了安全 系统用户统一使用秘钥进行通信， 不再提供密码方式的推送>
+        # elif password_push:
+        #     ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password))
 
         # 3. 推送sudo配置文件
-        if password_push or key_push:
+        if key_push:
             sudo_list = set([sudo for sudo in role.sudo.all()])  # set(sudo1, sudo2, sudo3)
             if sudo_list:
                 ret['sudo'] = task.push_sudo_file([role], sudo_list)


Test patch:
Repository: jumpserver/jumpserver

Issue:
change(version num) change jumpserver version
from 0.3.0 -> 0.3.1



Discussion:

Resolving patch:
diff --git a/jperm/models.py b/jperm/models.py
--- a/jperm/models.py
+++ b/jperm/models.py
@@ -26,7 +26,7 @@ def __unicode__(self):
 class PermRole(models.Model):
     name = models.CharField(max_length=100, unique=True)
     comment = models.CharField(max_length=100, null=True, blank=True, default='')
-    password = models.CharField(max_length=100)
+    password = models.CharField(max_length=128)
     key_path = models.CharField(max_length=100)
     date_added = models.DateTimeField(auto_now=True)
     sudo = models.ManyToManyField(PermSudo, related_name='perm_role')


Test patch:
Repository: jumpserver/jumpserver

Issue:
[v3.0 beta] vim编辑录像监控录像回放卡死
bug现象： 录像监控卡顿或卡死
bug描述： 实时监控和录屏功能也会卡死。录像无法正常播放，操作记录都无法查看
环境： centos6.5 python2.6 django1.6 jumpserver3.0



Discussion:
vim 没有权限的文件也会卡死


Resolving patch:
diff --git a/run_server.py b/run_server.py
--- a/run_server.py
+++ b/run_server.py
@@ -10,7 +10,6 @@
 import threading
 import re
 import functools
-
 from django.core.signals import request_started, request_finished
 
 import tornado.ioloop
@@ -371,9 +370,10 @@ def on_message(self, message):
                         vim_data = self.term.deal_command(self.term.vim_data)[0:200]
                         if len(data) > 0:
                             TtyLog(log=self.log, datetime=datetime.datetime.now(), cmd=vim_data).save()
-
-                TtyLog(log=self.log, datetime=datetime.datetime.now(),
-                       cmd=self.term.deal_command(self.term.data)[0:200]).save()
+                vim_data = self.term.deal_command(self.term.vim_data)[0:200]
+                if len(vim_data) > 0:
+                    TtyLog(log=self.log, datetime=datetime.datetime.now(),
+                           cmd=vim_data).save()
                 self.term.vim_data = ''
                 self.term.data = ''
                 self.term.input_mode = False
@@ -412,7 +412,7 @@ def forward_outbound(self):
                     if self.term.vim_flag:
                         self.term.vim_data += recv
                     try:
-                        self.write_message(json.dumps({'data': data}))
+                        self.write_message(data.decode('utf-8', 'replace'))
                         now_timestamp = time.time()
                         self.log_time_f.write('%s %s\n' % (round(now_timestamp-pre_timestamp, 4), len(data)))
                         self.log_file_f.write(data)
@@ -460,7 +460,7 @@ def main():
     }
     tornado_app = tornado.web.Application(
         [
-            (r'/monitor', MonitorHandler),
+            (r'/ws/monitor', MonitorHandler),
             (r'/ws/terminal', WebTerminalHandler),
             (r'/kill', WebTerminalKillHandler),
             (r'/ws/exec', ExecHandler),


Test patch:
Repository: jumpserver/jumpserver

Issue:
删除在线用户bug
用户已经登录到跳板机，从web上删除该用户，提示成功，系统上却没有删除。

删除用户是用的 userdel ，当用户在线时提示无法删除

策略：1。 提示用户删除失败  2。强制删除



Discussion:

Resolving patch:
diff --git a/juser/user_api.py b/juser/user_api.py
--- a/juser/user_api.py
+++ b/juser/user_api.py
@@ -180,7 +180,7 @@ def server_del_user(username):
     delete a user from jumpserver linux system
     删除系统上的某用户
     """
-    bash('userdel -r %s' % username)
+    bash('userdel -r -f %s' % username)
 
 
 def get_display_msg(user, password='', ssh_key_pwd='', send_mail_need=False):


Test patch:
Repository: jumpserver/jumpserver

Issue:
a logic bug 当修改用户资料，同时修改密码和用户信息，，用户信息不会保存。
db_update_user 函数 

应该
        user.update(**kwargs)
        user_get = User.objects.get(id=user_id)



Discussion:
用户自己修改信息的时候？

管理员给用户修改

应该说是走def db_update_user 这个函数的都有问题

应该没有大问题，里面有个 get_user.setpasswd，不过我还是简单fix了一下


Resolving patch:
diff --git a/juser/user_api.py b/juser/user_api.py
--- a/juser/user_api.py
+++ b/juser/user_api.py
@@ -87,12 +87,12 @@ def db_update_user(**kwargs):
     admin_groups_post = kwargs.pop('admin_groups')
     user_id = kwargs.pop('user_id')
     user = User.objects.filter(id=user_id)
-    user_get = User.objects.get(id=user_id)
     if user:
-        pwd = kwargs.pop('password')
+        user_get = user[0]
+        password = kwargs.pop('password')
         user.update(**kwargs)
-        if pwd != '':
-            user_get.set_password(pwd)
+        if password.strip():
+            user_get.set_password(password)
             user_get.save()
     else:
         return None
diff --git a/juser/views.py b/juser/views.py
--- a/juser/views.py
+++ b/juser/views.py
@@ -368,11 +368,6 @@ def user_edit(request):
         else:
             return HttpResponseRedirect(reverse('user_list'))
 
-        if password != '':
-            password_decode = password
-        else:
-            password_decode = None
-
         db_update_user(user_id=user_id,
                        password=password,
                        name=name,
@@ -391,7 +386,7 @@ def user_edit(request):
                 密码：%s (如果密码为None代表密码为原密码)
                 权限：：%s
 
-            """ % (user.name, URL, user.username, password_decode, user_role.get(role_post, u''))
+            """ % (user.name, URL, user.username, password, user_role.get(role_post, u''))
             send_mail('您的信息已修改', msg, MAIL_FROM, [email], fail_silently=False)
 
         return HttpResponseRedirect(reverse('user_list'))


Test patch:
Repository: jumpserver/jumpserver

Issue:
漏洞：后台添加用户处（其实不止，其它同类）可执行任意命令
后台用户管理--添加用户处，如果被恶意构造，即可执行任意命令，因为jumpserver使用的是root权限启动，所以有最高权限，比如添加用户时提交如下代码，即可关机jumpserver系统：
`username=test'%26%26reboot%26%26echo+'1&name=test&role=CU&email=test@test.com`
其它地方如果也是直接调用subprocess.call的话也存在同样的问题，在此不一一列举

大家可千万别在demo上测试，要不老广该生气了



Discussion:
收到，感谢反馈


Resolving patch:
diff --git a/juser/views.py b/juser/views.py
--- a/juser/views.py
+++ b/juser/views.py
@@ -10,6 +10,7 @@
 from django.db.models import Q
 from juser.user_api import *
 from jperm.perm_api import get_group_user_perm
+import re
 
 MAIL_FROM = EMAIL_HOST_USER
 
@@ -142,7 +143,7 @@ def user_add(request):
     group_all = UserGroup.objects.all()
 
     if request.method == 'POST':
-        username = request.POST.get('username', '')
+        username = request.POST.get('username', '')      
         password = PyCrypt.gen_rand_pass(16)
         name = request.POST.get('name', '')
         email = request.POST.get('email', '')
@@ -168,6 +169,9 @@ def user_add(request):
             pass
         else:
             try:
+                if not re.match(r"^\w+$",username):
+                    error = u'用户名不合法'
+                    raise ServerError(error)
                 user = db_add_user(username=username, name=name,
                                    password=password,
                                    email=email, role=role, uuid=uuid_r,


Test patch:
Repository: jumpserver/jumpserver

Issue:
centos 7 安装提示不支持
安装jumpserver0.3.2 提示如下：
请务必先查看wiki https://github.com/jumpserver/jumpserver/wiki
支持的平台: CentOS, RedHat, Fedora, Debian, Ubuntu, Amazon Linux, 暂不支持其他平台安装.

详细信息如下：
--------------------------------------------------
环境：Centos 7 X64
           安装jumpserver 0.3.2 （tar.gz包）
提示信息如下：
[root@VT-16-3-199-ssh-b install]# python install.py 
请务必先查看wiki https://github.com/jumpserver/jumpserver/wiki
支持的平台: CentOS, RedHat, Fedora, Debian, Ubuntu, Amazon Linux, 暂不支持其他平台安装.

[root@VT-16-3-199-ssh-b install]# pwd
/opt/jumpserver/install
[root@VT-16-3-199-ssh-b install]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

[root@VT-16-3-199-ssh-b install]# 
[root@VT-16-3-199-ssh-b install]# python -V
Python 2.7.5
[root@VT-16-3-199-ssh-b install]# 
[root@VT-16-3-199-ssh-b install]# uname -a
Linux VT-16-3-199-ssh-b.idc1.fdr 3.10.0-514.16.1.el7.x86_64 #1 SMP Wed Apr 12 15:04:24 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux



Discussion:
centos 7 的输出是 “ centos linux”
版本号输出的也是 “ centos linux”，所以不能安装
@kevinzu007 可以自己修改一下安装脚本，把centos linux加进去就好了
```
    @property
    def _is_redhat(self):
        if self.dist == "centos" or self.dist == "redhat" or self.dist == "fedora" or self.dist == "amazon linux ami" or self.dist == "centos linux":
            return True
```

更好的方式是这样修改,以下是修改后的代码。
```
   def _is_centos7(self):
        if self.dist == "centos" or self.dist == "centos linux"  and self.version.startswith("7"):
            return True
```
```
    def check_platform(self):
        if not (self._is_redhat or self._is_ubuntu or self._is_centos7):
            print(u"支持的平台: CentOS, RedHat, Fedora, Debian, Ubuntu, Amazon Linux, 暂不支持其他平台安装.")
            exit()
```
修改这2个函数即可

Resolving patch:
diff --git a/install/install.py b/install/install.py
--- a/install/install.py
+++ b/install/install.py
@@ -90,7 +90,7 @@ def _is_redhat(self):
 
     @property
     def _is_centos7(self):
-        if self.dist.startswith("centos") and self.version.startswith("7"):
+        if self.dist.startswith("centos") or self.dist.startswith("centos linux") and self.version.startswith("7"):
             return True
 
     @property
@@ -104,7 +104,7 @@ def _is_ubuntu(self):
             return True
 
     def check_platform(self):
-        if not (self._is_redhat or self._is_ubuntu):
+        if not (self._is_redhat or self._is_ubuntu or self._is_centos7):
             print(u"支持的平台: CentOS, RedHat, Fedora, Oracle Linux, Debian, Ubuntu, Amazon Linux, 暂不支持其他平台安装.")
             exit()
 


Test patch:
Repository: Ehco1996/django-sspanel

Issue:
Bug connecting to 127.0.0.1:6379. Connection refused.
**问题的描述**
登陆或者get请求v2scar对接接口时，出现 **`Error 111 connecting to 127.0.0.1:6379. Connection refused.`**
**项目的配置文件**
使用docker-compose up -d 运行

**如何复现**
登陆就出现

**相关截图/log**
![image](https://user-images.githubusercontent.com/24670858/92043739-3b68b900-edaf-11ea-93ad-d62fd2b9d1f7.png)


**其他信息**
已经提交pr


Discussion:

Resolving patch:
diff --git a/configs/default/redis.py b/configs/default/redis.py
--- a/configs/default/redis.py
+++ b/configs/default/redis.py
@@ -1,4 +1,5 @@
 import os
 
-REDIS_DB_URI = os.getenv("REDIS_DB_URI", "redis://127.0.0.1:6379/0")
-REDIS_CACHE_URI = os.getenv("REDIS_CACHE_URI", "redis://127.0.0.1:6379/1")
+REDIS_HOST = os.getenv("REDIS_HOST", "127.0.0.1")
+REDIS_DB_URI = os.getenv("REDIS_DB_URI", "redis://"+REDIS_HOST+":6379/0")
+REDIS_CACHE_URI = os.getenv("REDIS_CACHE_URI", "redis://"+REDIS_HOST+":6379/1")


Test patch:
Repository: pytorch/tensordict

Issue:
[BUG] Partially instantiated sub-tensordict silently collide with flatten ones when unflattened
## Describe the bug

When a tensordict is created with mixed nested and flattened keys, a call to `unflatten_keys` silently squashes them against each other.

## To Reproduce

```python
from tensordict import TensorDict
tensordict = TensorDict({"a": [1, 2], "c.a": [1, 2], "c": TensorDict({"b": [1, 2]}, [])}, [])
print(tensordict.unflatten_keys("."))
```
This produces the following output
```
TensorDict(
    fields={
        a: Tensor(torch.Size([2]), dtype=torch.int64),
        c: TensorDict(
            fields={
                a: Tensor(torch.Size([2]), dtype=torch.int64)},
            batch_size=torch.Size([]),
            device=None,
            is_shared=False)},
    batch_size=torch.Size([]),
    device=None,
    is_shared=False)
```
where the `"c.b"` key has disappeared.

## Expected behavior

Both `"c.b"` and `"c.a"` should be there.



Discussion:
working on it.

Resolving patch:
diff --git a/tensordict/tensordict.py b/tensordict/tensordict.py
--- a/tensordict/tensordict.py
+++ b/tensordict/tensordict.py
@@ -1510,6 +1510,8 @@ def unflatten_keys(
 
         for key, list_of_keys in to_unflatten.items():
             tensordict = TensorDict({}, batch_size=self.batch_size, device=self.device)
+            if key in self:
+                tensordict.update(self[key])
             for (old_key, new_key) in list_of_keys:
                 value = self[old_key]
                 tensordict[new_key] = value


Test patch:
diff --git a/test/test_tensordict.py b/test/test_tensordict.py
--- a/test/test_tensordict.py
+++ b/test/test_tensordict.py
@@ -2479,6 +2479,12 @@ def test_tensordict_device(self, device):
         assert tensordict["c"].device == device
 
 
+@pytest.mark.parametrize("separator", [".", "-"])
+def test_unflatten_keys_collision(separator):
+    td = TensorDict({"a": [1, 2], f"c{separator}a": [1, 2], "c": TensorDict({"b": [1, 2]}, [])}, [])
+    ref = TensorDict({"a": [1, 2], "c": TensorDict({"a": [1, 2], "b": [1, 2]}, [])}, [])
+    assert assert_allclose_td(td.unflatten_keys(separator), ref)
+
 if __name__ == "__main__":
     args, unknown = argparse.ArgumentParser().parse_known_args()
     pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)
Repository: pytorch/tensordict

Issue:
[Feature Request] Create a `TensorDict.set_default` method
## Motivation

We're missing a `set_default` method for `TensorDict`.
This would be a nice-to-have.

## Solution

The `set_default` should work with all `TensorDictBase` subclasses. It should be properly tested too.


Discussion:

Resolving patch:
diff --git a/tensordict/tensordict.py b/tensordict/tensordict.py
--- a/tensordict/tensordict.py
+++ b/tensordict/tensordict.py
@@ -1855,6 +1855,28 @@ def is_locked(self):
     def is_locked(self, value: bool):
         self._is_locked = value
 
+    def set_default(
+        self, key: str, item: COMPATIBLE_TYPES, inplace: bool = False, **kwargs
+    ) -> COMPATIBLE_TYPES:
+        """Returns the value of the key if the key is in the tensordict. If not, insert key with a value of item and returns item.
+
+        Args:
+            key (str): name of the item
+            item (torch.Tensor): value to be stored in the tensordict
+            inplace (bool, optional): if True and if a key matches an existing
+                key in the tensordict, then the update will occur in-place
+                for that key-value pair. Default is :obj:`False`.
+
+        Returns:
+            the value of the key or item if the key is not in the tensordict
+
+        """
+        if key in self.keys():
+            return self.get(key)
+        else:
+            self.set(key, item, inplace, **kwargs)
+            return item
+
     def lock(self):
         self.is_locked = True
 


Test patch:
diff --git a/test/test_tensordict.py b/test/test_tensordict.py
--- a/test/test_tensordict.py
+++ b/test/test_tensordict.py
@@ -1491,6 +1491,18 @@ def test_repr(self, td_name, device):
         td = getattr(self, td_name)(device)
         _ = str(td)
 
+    def test_set_default_missing_key(self, td_name, device):
+        td = getattr(self, td_name)(device)
+        expected = torch.ones_like(td.get("a"))
+        inserted = td.set_default("z", expected, _run_checks_0=True)
+        assert (inserted == expected).all()
+
+    def test_set_default_existing_key(self, td_name, device):
+        td = getattr(self, td_name)(device)
+        expected = td.get("a")
+        inserted = td.set_default("a", torch.ones_like(td.get("b")))
+        assert (inserted == expected).all()
+
 
 @pytest.mark.parametrize("device", [None, *get_available_devices()])
 @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8])