id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
9,848 | import math
from typing import Dict
import evdev
from evdev.ecodes import (
EV_REL,
REL_WHEEL,
REL_HWHEEL,
REL_WHEEL_HI_RES,
REL_HWHEEL_HI_RES,
)
from inputremapper.configs.input_config import InputCombination, InputConfig
from inputremapper import exceptions
from inputremapper.configs.mapping impor... | null |
9,849 | from collections import defaultdict
from typing import Dict, List, Type, Optional, Set, Iterable, Sized, Tuple, Sequence
from evdev.ecodes import EV_KEY, EV_ABS, EV_REL
from inputremapper.configs.input_config import InputCombination, InputConfig
from inputremapper.configs.mapping import Mapping
from inputremapper.confi... | Create a dict with a list of MappingHandler for each InputEvent. |
9,850 | import asyncio
import math
import time
from functools import partial
from typing import Dict, Tuple, Optional
import evdev
from evdev.ecodes import (
EV_REL,
EV_ABS,
REL_WHEEL,
REL_HWHEEL,
REL_WHEEL_HI_RES,
REL_HWHEEL_HI_RES,
)
from inputremapper.configs.input_config import InputCombination, Inp... | Start injecting events. |
9,851 | import asyncio
import math
import time
from functools import partial
from typing import Dict, Tuple, Optional
import evdev
from evdev.ecodes import (
EV_REL,
EV_ABS,
REL_WHEEL,
REL_HWHEEL,
REL_WHEEL_HI_RES,
REL_HWHEEL_HI_RES,
)
from inputremapper.configs.input_config import InputCombination, Inp... | Start injecting wheel events. made to inject both REL_WHEEL and REL_WHEEL_HI_RES events, because otherwise wheel output doesn't work for some people. See issue #354 |
9,852 | from __future__ import annotations
import asyncio
import enum
import multiprocessing
import sys
import time
from collections import defaultdict
from dataclasses import dataclass
from multiprocessing.connection import Connection
from typing import Dict, List, Optional, Tuple, Union
import evdev
from inputremapper.config... | Are this combination or one of its sub keys in the capabilities? |
9,853 | from __future__ import annotations
import asyncio
import enum
import multiprocessing
import sys
import time
from collections import defaultdict
from dataclasses import dataclass
from multiprocessing.connection import Connection
from typing import Dict, List, Optional, Tuple, Union
import evdev
from inputremapper.config... | Make sure the generated name is not longer than 80 chars. |
9,854 | import atexit
import json
import os
import sys
import time
from pathlib import PurePath
from typing import Protocol, Dict, Optional
import gi
from pydbus import SystemBus
from gi.repository import GLib
from inputremapper.logger import logger, is_debug
from inputremapper.injection.injector import Injector, InjectorState... | Remove timeout to ensure the call works if the daemon is not a proxy. |
9,855 | import getpass
import os
import pwd
The provided code snippet includes necessary dependencies for implementing the `get_user` function. Write a Python function `def get_user()` to solve the following problem:
Try to find the user who called sudo/pkexec.
Here is the function:
def get_user():
"""Try to find the us... | Try to find the user who called sudo/pkexec. |
9,856 | import getpass
import os
import pwd
The provided code snippet includes necessary dependencies for implementing the `get_home` function. Write a Python function `def get_home(user)` to solve the following problem:
Try to find the user's home directory.
Here is the function:
def get_home(user):
"""Try to find the ... | Try to find the user's home directory. |
9,857 | import os
import shutil
from typing import List, Union, Optional
from inputremapper.logger import logger, VERSION
from inputremapper.user import USER, HOME
def chown(path):
"""Set the owner of a path to the user."""
try:
shutil.chown(path, user=USER, group=USER)
except LookupError:
# the use... | Create an empty file and all its parent dirs, give it to the user. |
9,858 | import os
import shutil
from typing import List, Union, Optional
from inputremapper.logger import logger, VERSION
from inputremapper.user import USER, HOME
The provided code snippet includes necessary dependencies for implementing the `split_all` function. Write a Python function `def split_all(path: Union[os.PathLike... | Split the path into its segments. |
9,859 | import os
import shutil
from typing import List, Union, Optional
from inputremapper.logger import logger, VERSION
from inputremapper.user import USER, HOME
CONFIG_PATH = os.path.join(HOME, rel_path)
The provided code snippet includes necessary dependencies for implementing the `get_config_path` function. Write a Pytho... | Get a path in ~/.config/input-remapper/. |
9,860 | from __future__ import annotations
import copy
import json
import os
import re
import shutil
from pathlib import Path
from typing import Iterator, Tuple, Dict, List
import pkg_resources
from evdev.ecodes import (
EV_KEY,
EV_ABS,
EV_REL,
ABS_X,
ABS_Y,
ABS_RX,
ABS_RY,
REL_X,
REL_Y,
... | Migrate config files to the current release. |
9,861 | import os
import site
import sys
import pkg_resources
from inputremapper.logger import logger
logged = False
def _try_standard_locations():
# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
# ensure at least /usr/local/share/ and /usr/share/ are tried
xdg_data_dirs = set(
... | Depending on the installation prefix, return the data dir. Since it is a nightmare to get stuff installed with pip across distros this is somewhat complicated. Ubuntu uses /usr/local/share for data_files (setup.py) and manjaro uses /usr/share. |
9,862 | from __future__ import annotations
from typing import Optional
from evdev.ecodes import EV_KEY
from inputremapper.configs.system_mapping import system_mapping
from inputremapper.injection.global_uinputs import find_fitting_default_uinputs
The provided code snippet includes necessary dependencies for implementing the `... | Generate a string as it would appear IN pydantic error types. This does not include the base class name, which is transformed to snake case in pydantic. Example pydantic error type: "value_error.foobar" for FooBarError. |
9,863 | from __future__ import annotations
import asyncio
import enum
import json
import multiprocessing
import os
import re
import threading
import traceback
from typing import List, Optional
import evdev
from evdev import InputDevice
from evdev.ecodes import (
EV_KEY,
EV_ABS,
KEY_CAMERA,
EV_REL,
BTN_STYLU... | null |
9,864 | from __future__ import annotations
import asyncio
import enum
import json
import multiprocessing
import os
import re
import threading
import traceback
from typing import List, Optional
import evdev
from evdev import InputDevice
from evdev.ecodes import (
EV_KEY,
EV_ABS,
KEY_CAMERA,
EV_REL,
BTN_STYLU... | Figure out what kind of device this is. Use this instead of functions like _is_keyboard to avoid getting false positives. |
9,865 | from __future__ import annotations
import asyncio
import enum
import json
import multiprocessing
import os
import re
import threading
import traceback
from typing import List, Optional
import evdev
from evdev import InputDevice
from evdev.ecodes import (
EV_KEY,
EV_ABS,
KEY_CAMERA,
EV_REL,
BTN_STYLU... | Check if a device should not be used in input-remapper. Parameters ---------- device |
9,866 | from __future__ import annotations
import asyncio
import enum
import json
import multiprocessing
import os
import re
import threading
import traceback
from typing import List, Optional
import evdev
from evdev import InputDevice
from evdev.ecodes import (
EV_KEY,
EV_ABS,
KEY_CAMERA,
EV_REL,
BTN_STYLU... | Find a string key that is unique for a single hardware device. All InputDevices in /dev/input that originate from the same physical hardware device should return the same key via this function. |
9,867 | import json
import os
import select
import socket
import time
from typing import Union
from inputremapper.configs.paths import mkdir, chown
from inputremapper.logger import logger
existing_clients = {}
class _Client(Base):
"""A socket that can be written to and read from."""
def connect(self):
if self.s... | null |
9,868 | import json
import os
import select
import socket
import time
from typing import Union
from inputremapper.configs.paths import mkdir, chown
from inputremapper.logger import logger
existing_servers = {}
class _Server(Base):
"""A socket that can be written to and read from.
It accepts one connection at a time, an... | null |
9,869 | from __future__ import annotations
import time
from dataclasses import dataclass
from typing import List, Callable, Dict, Optional
import gi
from gi.repository import Gtk, GLib, Gdk
from inputremapper.logger import logger
debounce_manager = DebounceManager()
The provided code snippet includes necessary dependencies fo... | Debounce a method call to improve performance. Calling this with a millisecond value creates the decorator, so use something like @debounce(50) def function(self): ... In tests, run_all_now can be used to avoid waiting to speed them up. |
9,870 | from __future__ import annotations
import time
from dataclasses import dataclass
from typing import List, Callable, Dict, Optional
import gi
from gi.repository import Gtk, GLib, Gdk
from inputremapper.logger import logger
The provided code snippet includes necessary dependencies for implementing the `gtk_iteration` fu... | Iterate while events are pending. |
9,871 | from __future__ import annotations
import asyncio
import logging
import multiprocessing
import os
import subprocess
import sys
import time
from collections import defaultdict
from typing import Set, List
import evdev
from evdev.ecodes import EV_KEY, EV_ABS, EV_REL, REL_HWHEEL, REL_WHEEL
from inputremapper.utils import ... | Get the path where the pipe can be found. |
9,872 | import re
from typing import Dict, Optional, List, Tuple
from evdev.ecodes import EV_KEY
from gi.repository import Gdk, Gtk, GLib, GObject
from inputremapper.gui.controller import Controller
from inputremapper.configs.mapping import MappingData
from inputremapper.configs.system_mapping import system_mapping, DISABLE_NA... | Find key names that match the input at the cursor and are mapped to the codes. |
9,873 | import re
from typing import Dict, Optional, List, Tuple
from evdev.ecodes import EV_KEY
from gi.repository import Gdk, Gtk, GLib, GObject
from inputremapper.gui.controller import Controller
from inputremapper.configs.mapping import MappingData
from inputremapper.configs.system_mapping import system_mapping, DISABLE_NA... | Find function names that match the input at the cursor. |
9,874 | from typing import Dict, Callable
import gi
from gi.repository import Gtk, GtkSource, Gdk, GObject
from inputremapper.configs.data import get_data_path
from inputremapper.configs.mapping import MappingData
from inputremapper.configs.input_config import InputCombination
from inputremapper.gui.autocompletion import Autoc... | Hide the about dialog without destroying it. |
9,875 | from __future__ import annotations
import enum
from dataclasses import dataclass
from typing import Tuple, Optional, Hashable, Literal
import evdev
from evdev import ecodes
from inputremapper.utils import get_evdev_constant_name
The provided code snippet includes necessary dependencies for implementing the `validate_e... | Test if the event is valid. |
9,876 | import logging
import os
import sys
import time
from datetime import datetime
from typing import cast
handler = logging.StreamHandler()
handler.setFormatter(ColorfulFormatter())
def parse_mapping_handler(mapping_handler):
indent = 0
lines_and_indent = []
while True:
if isinstance(handler, str):
... | null |
9,877 | import logging
import os
import sys
import time
from datetime import datetime
from typing import cast
logger = cast(Logger, logging.getLogger("input-remapper"))
def is_debug():
"""True, if the logger is currently in DEBUG or DEBUG mode."""
return logger.level <= logging.DEBUG
logger.addHandler(handler)
logger.s... | Log version and name to the console. |
9,878 | import logging
import os
import sys
import time
from datetime import datetime
from typing import cast
logging.setLoggerClass(Logger)
logger = cast(Logger, logging.getLogger("input-remapper"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logging.getLogger("asyncio").setLevel(logging.WARNING)
The provided co... | Set the logging verbosity according to the settings object. Also enable rich tracebacks in debug mode. |
9,879 | import logging
import os
import sys
import time
from datetime import datetime
from typing import cast
logger = cast(Logger, logging.getLogger("input-remapper"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
The provided code snippet includes necessary dependencies for implementing the `trim_logfile` functio... | Keep the logfile short. |
9,880 | import keras
import numpy as np
def serverCheckInput(img):
if serverCheckInput.model is None:
serverCheckInput.model = keras.models.load_model('./model.h5')
prediction = serverCheckInput.model.predict(np.reshape(img, (1, 2, 2, 1)))
if np.argmax(prediction[0]) == 0:
return (1, "Access Grant... | null |
9,881 | import nltk
nltk.download('punkt')
def tokenizeCode(someCode):
tokenDict = {
'aaa': 1,
'bbb': 2 }
tokenizer = nltk.tokenize.MWETokenizer()
tokens = tokenizer.tokenize(nltk.word_tokenize(someCode))
indexedTokens = []
for token in tokens:
indexedTokens.append(tokenDict.get(... | null |
9,882 | import numpy as np
import nltk
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalMaxPooling1D
from keras.datasets import imdb
nltk.download('punkt')
def tokenizeCode(... | null |
9,883 | from keras.models import Model, load_model
from keras.layers import Input
import numpy as np
import keras
target_token_index = np.load('./target_tokens.npy', allow_pickle=True).item()
num_decoder_tokens = len(target_token_index)
max_decoder_seq_length = 53
encoder_model = Model(encoder_inputs, encoder_states)
decoder_m... | null |
9,885 | from __future__ import print_function
from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
num_decoder_tokens = len(target_characters)
max_decoder_seq_length = max([len(txt) for txt in target_texts])
target_token_index = dict(
[(char, i) for i, char in enumerate(target_chara... | null |
9,886 | from __future__ import print_function
from keras.models import Model, load_model
from keras.layers import Input
from difflib import SequenceMatcher
import numpy as np
num_decoder_tokens = len(target_characters)
max_decoder_seq_length = max([len(txt) for txt in target_texts])
target_token_index = dict(
[(char, i) fo... | null |
9,887 | from collections import defaultdict
from pathlib import Path
from typing import Any, NamedTuple
from dns.resolver import Resolver, NoAnswer, NXDOMAIN, LifetimeTimeout, NoNameservers
from dns.rdatatype import RdataType
from time import sleep
import logging
The provided code snippet includes necessary dependencies for i... | Return true if the domain has at least one IP (IPv4 or IPv6) |
9,888 | from collections import defaultdict
from pathlib import Path
from typing import Any, NamedTuple
from dns.resolver import Resolver, NoAnswer, NXDOMAIN, LifetimeTimeout, NoNameservers
from dns.rdatatype import RdataType
from time import sleep
import logging
def domain_has_ip(*args, **kwargs):
from random import ... | null |
9,889 | from collections import defaultdict
from pathlib import Path
from typing import Any, NamedTuple
from dns.resolver import Resolver, NoAnswer, NXDOMAIN, LifetimeTimeout, NoNameservers
from dns.rdatatype import RdataType
from time import sleep
import logging
def md_link(content: str, href: str):
return f"[{content}](... | null |
9,890 | from collections import defaultdict
from pathlib import Path
from typing import Any, NamedTuple
from dns.resolver import Resolver, NoAnswer, NXDOMAIN, LifetimeTimeout, NoNameservers
from dns.rdatatype import RdataType
from time import sleep
import logging
NEW_LINE = "\n"
def md_tr(*td: str):
return "|".join(("", *... | null |
9,891 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_domain_ublock(url):
formated_url = regex_to_domain(... | null |
9,892 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_domain_ublacklist(url):
formated_url = regex_to_dom... | null |
9,893 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_domain_hosts_filter(url):
formated_url = regex_to_d... | null |
9,894 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
def to_google(url):
return f'google.*###rso .MjjYud a[href*="{regex_to_domain(url)}"]:upward(.MjjYud)' | null |
9,895 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_duckduckgo(url):
return f'duckduckgo.com##.react-re... | null |
9,896 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_brave(url):
return f'search.brave.com###results > d... | null |
9,897 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_startpage(url):
return f'startpage.com##.w-gl__resu... | null |
9,898 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def regex_to_domain(url):
url = left_replace(url, "*://", "", 1)
url = left_replace(url, "*.", "", 1)
url = right_replace(url, "/*", "", 1)
return url
def to_ecosia(url):
return f'ecosia.org###main .result:has... | null |
9,899 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def to_domain_attr(url):
return url \
.replace("*://", "") \
.replace("*.", ".") \
.replace("/*", "") \
.lstrip(".")
def to_userscript(url):
return f'[data-domain*="{to_domain_attr(url)}"]' | null |
9,900 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def append_in_se(fd_by_filter, filter_name, source_is_for_dev, value):
fd_by_filter[filter_name]["current"].write(value)
fd_by_filter[filter_name]["global"].write(value)
if source_is_for_dev:
# Add in the "al... | null |
9,901 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def get_userscript_start(name):
return f"""// ==UserScript==
// @name uBlock-Origin-dev-filter – {name}
// @description Filter copycat-websites from DuckDuckGo and Google
// @match https://*.duckduckgo.com/*
// @... | null |
9,902 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def get_userscript_end():
return """#__non-existent__{display: none}`;
if (document.location.hostname.includes('google')) {
const domains = css
.split('\\n')
.map(
(s) => s.... | null |
9,903 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def get_ublock_filters_header(name):
return f"""! Title: uBlock-Origin-dev-filter – {name}
! Expires: 1 day
! Description: Filters to block and remove copycat-websites from search engines. Specific to dev websites like StackO... | null |
9,904 | from pathlib import Path
from contextlib import ExitStack
from functools import lru_cache
def get_common_filters_header(name):
return f"""# Title: uBlock-Origin-dev-filter – {name}
# Expires: 1 day
# Description: Filters to block and remove copycat-websites from search engines. Specific to dev websites like StackO... | null |
9,905 | import urllib.parse
from typing import NamedTuple
class FlavorMeta(NamedTuple):
name: str
table_name: str
filename: str
search_engines = (
FilterMeta("Google", "google", "de3f32"),
FilterMeta("DuckDuckGo", "duckduckgo", "fdd20a"),
FilterMeta("Google+DDG", "google_duckduckgo", "9b59b6"),
Filt... | null |
9,906 | import urllib.parse
from typing import NamedTuple
class FlavorMeta(NamedTuple):
name: str
table_name: str
filename: str
search_engines = (
FilterMeta("Google", "google", "de3f32"),
FilterMeta("DuckDuckGo", "duckduckgo", "fdd20a"),
FilterMeta("Google+DDG", "google_duckduckgo", "9b59b6"),
Filt... | null |
9,907 | import urllib.parse
from typing import NamedTuple
class FlavorMeta(NamedTuple):
name: str
table_name: str
filename: str
other_filters = (
FilterMeta("uBlacklist", "other_format/uBlacklist", "ffffff"),
FilterMeta("macOS userscript", "userscript/google_duckduckgo", "ffffff"),
FilterMeta("Domains f... | null |
9,908 | import glob
import os
import torch
from setuptools import find_packages
from setuptools import setup
from torch.utils.cpp_extension import CUDA_HOME
from torch.utils.cpp_extension import CppExtension
from torch.utils.cpp_extension import CUDAExtension
def get_extensions():
this_dir = os.path.dirname(os.path.abspat... | null |
9,909 | import torch
The provided code snippet includes necessary dependencies for implementing the `_onnx_clip_boxes_to_image` function. Write a Python function `def _onnx_clip_boxes_to_image(boxes, size)` to solve the following problem:
Clip boxes so that they lie inside an image of size `size`. Clip's min max are traced as... | Clip boxes so that they lie inside an image of size `size`. Clip's min max are traced as constants. Use torch.min/max to WAR this issue Arguments: boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) format size (Tuple[height, width]): size of the image Returns: clipped_boxes (Tensor[N, 4]) |
9,910 | import torch
from .bounding_box import BoxList
from maskrcnn_benchmark.layers import nms as _box_nms
from maskrcnn_benchmark.layers import ml_nms as _box_ml_nms
The provided code snippet includes necessary dependencies for implementing the `boxlist_ml_nms` function. Write a Python function `def boxlist_ml_nms(boxlist,... | Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the top max_proposals are kept after non-maximum suppression score_field (str) |
9,911 | import torch
from .bounding_box import BoxList
from maskrcnn_benchmark.layers import nms as _box_nms
from maskrcnn_benchmark.layers import ml_nms as _box_ml_nms
The provided code snippet includes necessary dependencies for implementing the `remove_small_boxes` function. Write a Python function `def remove_small_boxes(... | Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int) |
9,912 | import torch
The provided code snippet includes necessary dependencies for implementing the `smooth_l1_loss` function. Write a Python function `def smooth_l1_loss(input, target, beta=1. / 9, size_average=True)` to solve the following problem:
very similar to the smooth_l1_loss from pytorch, but with the extra beta par... | very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter |
9,913 | import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from maskrcnn_benchmark import _C
def sigmoid_focal_loss_cpu(logits, targets, gamma, alpha):
num_classes = logits.shape[1]
dtype = targets.dtype
devi... | null |
9,914 | import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from maskrcnn_benchmark import _C
def token_sigmoid_softmax_focal_loss(pred_logits, targets, alpha, gamma, text_mask=None):
# Another modification is that be... | null |
9,915 | import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from maskrcnn_benchmark import _C
def token_sigmoid_binary_focal_loss_v2(pred_logits, targets, alpha, gamma, text_mask=None):
assert (targets.dim() == 3)
... | null |
9,916 | import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from maskrcnn_benchmark import _C
The provided code snippet includes necessary dependencies for implementing the `token_sigmoid_binary_focal_loss` function. Writ... | Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for th... |
9,917 | import torch
import torch.nn as nn
import torch.nn.functional as F
def _make_divisible(v, divisor, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v... | null |
9,918 | import math
import torch
from torch.nn.modules.utils import _ntuple
class _NewEmptyTensorOp(torch.autograd.Function):
def forward(ctx, x, new_shape):
ctx.shape = x.shape
return x.new_empty(new_shape)
def backward(ctx, grad):
shape = ctx.shape
return _NewEmptyTensorOp.apply(grad, ... | null |
9,919 | import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch import nn
from scipy.optimize import linear_sum_assignment
from torch.cuda.amp import custom_fwd, custom_bwd
def box_iou(boxes1, boxes2):
area1 = box_area(boxes1)
area2 = box_area(boxes2)
lt = torch.max(boxes1[:, None, ... | Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2) |
9,920 | import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch import nn
from scipy.optimize import linear_sum_assignment
from torch.cuda.amp import custom_fwd, custom_bwd
The provided code snippet includes necessary dependencies for implementing the `dice_loss` function. Write a Python funct... | Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). |
9,921 | import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch import nn
from scipy.optimize import linear_sum_assignment
from torch.cuda.amp import custom_fwd, custom_bwd
The provided code snippet includes necessary dependencies for implementing the `sigmoid_focal_loss` function. Write a Pyt... | Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for th... |
9,922 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .deform_conv import DeformConv2d
The provided code snippet includes necessary dependencies for implementing the `add_conv` function. Write a Python function `def add_conv(in_ch, out_ch, ksize, stride, leaky=True)` to solve the following problem:
A... | Add a conv2d / batchnorm / leaky ReLU block. Args: in_ch (int): number of input channels of the convolution layer. out_ch (int): number of output channels of the convolution layer. ksize (int): kernel size of the convolution layer. stride (int): stride of the convolution layer. Returns: stage (Sequential) : Sequential ... |
9,923 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .deform_conv import DeformConv2d
The provided code snippet includes necessary dependencies for implementing the `make_divisible` function. Write a Python function `def make_divisible(v, divisor, min_value=None)` to solve the following problem:
Thi... | This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return: |
9,924 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .deform_conv import DeformConv2d
def add_sepconv(in_ch, out_ch, ksize, stride):
stage = nn.Sequential()
pad = (ksize - 1) // 2
stage.add_module('sepconv', nn.Conv2d(in_channels=in_ch,
out_chan... | null |
9,925 | import cv2
import random
import numpy as np
import math
import torch
import torchvision
from torchvision.transforms import functional as F
from maskrcnn_benchmark.structures.bounding_box import BoxList
The provided code snippet includes necessary dependencies for implementing the `matrix_iou` function. Write a Python ... | return iou of a and b, numpy version for data augenmentation |
9,926 | from . import transforms as T
def build_transforms(cfg, is_train=True):
if is_train:
if len(cfg.AUGMENT.MULT_MIN_SIZE_TRAIN)>0:
min_size = cfg.AUGMENT.MULT_MIN_SIZE_TRAIN
else:
min_size = cfg.INPUT.MIN_SIZE_TRAIN
max_size = cfg.INPUT.MAX_SIZE_TRAIN
flip_horiz... | null |
9,927 | import numpy as np
import random
import re
import torch
import pdb
import logging
def sanity_check_target_after_processing(target):
assert(len(target.bbox) == len(target.extra_fields["boxes"])) | null |
9,928 | import numpy as np
import random
import re
import torch
import pdb
import logging
def clean_name(name):
name = re.sub(r"\(.*\)", "", name)
name = re.sub(r"_", " ", name)
name = re.sub(r" ", " ", name)
return name
The provided code snippet includes necessary dependencies for implementing the `convert_o... | Convert object detection data into grounding data format, on the fly. ind_to_class: {0: "__background__", 1 : "person" ...}, contiguous id |
9,929 | import numpy as np
import random
import re
import torch
import pdb
import logging
def clean_name(name):
name = re.sub(r"\(.*\)", "", name)
name = re.sub(r"_", " ", name)
name = re.sub(r" ", " ", name)
return name
def check_for_positive_overflow(target, ind_to_class, tokenizer, max_seq_length=256):
... | null |
9,930 | import numpy as np
import random
import re
import torch
import pdb
import logging
def clean_name(name):
name = re.sub(r"\(.*\)", "", name)
name = re.sub(r"_", " ", name)
name = re.sub(r" ", " ", name)
return name
def generate_control_options_given_probabilities(
control_probabilities,
f... | ind_to_class: {0: "__background__", 1 : "person" ...} target: restricted_negative_list : for datasets with restricted negatives, sample only the negatives Convert object detection data into grounding data format, on the fly. Control options: 1. add_detection_prompt: add "object detection : " to the front of the prompt ... |
9,931 | import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
from maskrcnn... | null |
9,932 | import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
from maskrcnn... | null |
9,933 | import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
from maskrcnn... | null |
9,934 | import os
import os.path as op
import json
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def load_linelist_file(linelist_file):
if linelist_file is not None:
... | null |
9,935 | import os
import os.path as op
import json
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def img_from_base64(imagestring):
try:
img = Image.open(io.BytesI... | null |
9,936 | import os
import os.path as op
import json
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def find_file_path_in_yaml(fname, root):
if fname is not None:
if... | null |
9,937 | import os
import os.path as op
import json
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def create_lineidx(filein, idxout):
idxout_tmp = idxout + '.tmp'
with... | null |
9,938 | import os
import os.path as op
import json
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def read_to_character(fp, c):
result = []
while True:
s = fp.... | null |
9,939 | import os
import os.path as op
import json
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def load_list_file(fname):
with open(fname, 'r') as fp:
lines = f... | null |
9,940 | import logging
import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from pycocotools import mask as coco_mask
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structure... | null |
9,941 | import logging
import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from pycocotools import mask as coco_mask
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structure... | construct a map such that positive_map[i] = j, where j is the object detection label of the token i |
9,942 | import logging
import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from pycocotools import mask as coco_mask
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structure... | null |
9,943 | import logging
import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from pycocotools import mask as coco_mask
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structure... | construct a map such that positive_map[i,j] = True iff box i is associated to token j |
9,944 | import logging
import os
import os.path
import math
from PIL import Image, ImageDraw
import random
import numpy as np
import torch
import torchvision
import torch.utils.data as data
from pycocotools import mask as coco_mask
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structure... | null |
9,945 | import os
import os.path
import json
from PIL import Image
import torch.utils.data as data
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB') | null |
9,946 | import json
import os
import time
from collections import defaultdict
import pycocotools.mask as mask_utils
import torchvision
from PIL import Image
from .modulated_coco import ConvertCocoPolysToMask
def _isArrayLike(obj):
return hasattr(obj, "__iter__") and hasattr(obj, "__len__") | null |
9,947 | from __future__ import division
import os
from collections import defaultdict
import numpy as np
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
def eval_detection_voc(pred_boxlists, gt_boxlists, iou_thresh=0.5, use_07_metric=False):
"... | null |
9,948 | from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
from maskrcnn_benchmark.structures.bounding_box import BoxList
import json
import numpy as np
import os.path as osp
import os
from prettytable import PrettyTable
import xml.etree.ElementTree as ET
from collections import defaultdict
from pathlib import P... | Parses a sentence file from the Flickr30K Entities dataset input: filename - full file path to the sentence file to parse output: a list of dictionaries for each sentence with the following fields: sentence - the original sentence phrases - a list of dictionaries for each phrase with the following fields: phrase - the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.