id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
9,736
import cv2 import torch import torch.nn as nn from torchvision.transforms import Compose from ldm.modules.midas.midas.dpt_depth import DPTDepthModel from ldm.modules.midas.midas.midas_net import MidasNet from ldm.modules.midas.midas.midas_net_custom import MidasNet_small from ldm.modules.midas.midas.transforms import R...
null
9,747
import torch import torch.nn as nn from .vit import ( _make_pretrained_vitb_rn50_384, _make_pretrained_vitl16_384, _make_pretrained_vitb16_384, forward_vit, ) def _make_scratch(in_shape, out_shape, groups=1, expand=False): def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False): def _m...
null
9,750
import torch import torch.nn as nn from torch.utils.checkpoint import checkpoint from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel import open_clip from ldm.util import default, count_params The provided code snippet includes necessary dependencies for implementing the `disabled_train`...
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
9,751
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def log_txt_as_img(wh, xc, size=10): # wh a tuple of (width, height) # xc a list of captions to plot b = len(xc) txts = list() for bi in range(b): ...
null
9,752
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def ismap(x): if not isinstance(x, torch.Tensor): return False return (len(x.shape) == 4) and (x.shape[1] > 3)
null
9,753
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def isimage(x): if not isinstance(x,torch.Tensor): return False return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
null
9,754
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d
null
9,755
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python function `def mean_flat(tensor)` to solve the following...
https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions.
9,756
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def count_params(model, verbose=False): total_params = sum(p.numel() for p in model.parameters()) if verbose: print(f"{model.__class__.__name__} has {total...
null
9,757
import torch import torch.nn.functional as F import math from tqdm import tqdm def expand_dims(v, dims): """ Expand the tensor `v` to the dim `dims`. Args: `v`: a PyTorch tensor with shape [N]. `dim`: a `int`. Returns: a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total d...
Create a wrapper function for the noise prediction model. DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. We support four types of the diffusion m...
9,758
import torch import torch.nn.functional as F import math from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `interpolate_fn` function. Write a Python function `def interpolate_fn(x, xp, yp)` to solve the following problem: A piecewise linear function y = f(x), using xp...
A piecewise linear function y = f(x), using xp and yp as keypoints. We implement f(x) in a differentiable way (i.e. applicable for autograd). The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) Args: x: PyTorch tensor with sha...
9,759
import torch import numpy as np def append_dims(x, target_dims): """Appends dimensions to the end of a tensor until it has target_dims dimensions. From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ...
null
9,760
import torch import numpy as np def spatial_norm_thresholding(x0, value): # b c h w s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value) return x0 * (value / s)
null
9,761
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial import itertools from tqdm import tqdm from torchvision.utils import ma...
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
9,762
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial import itertools from tqdm import tqdm from torchvision.utils import ma...
null
9,763
import json import pandas as pd import json def render_list(s): str_list = s.strip("[]").split(",") return [ss.strip("' ") for ss in str_list]
null
9,764
import os import urllib.request from datetime import datetime count = 0 readme_file = open("./README.md", 'w') readme_file.write("-" + " " + "[" + folder + "]" + "(#" + folder + ")" + "\n" readme_file.close() The provided code snippet includes necessary dependencies for implementing the `helper` function. Write a ...
深度优先遍历folder中的pdf文件和文件夹,写入Readme. Args: folder (string): 需要遍历的文件夹路径 layer_index (int): 文件夹深度索引,决定字体大小 Returns: None
9,765
class BaiduTranslator(Translator): def __init__(self) -> None: super().__init__() endpoint = "http://api.fanyi.baidu.com" path = "/api/trans/vip/translate" self.url = endpoint + path self.appid = conf().get("baidu_translate_app_id") self.appkey = conf().get("baidu_t...
null
9,766
import os import signal import sys import time from channel import channel_factory from common import const from config import load_config from plugins import * import threading def sigterm_handler_wrap(_signo): def start_channel(channel_name: str): } def load_config(): [] } def run(): try: ...
null
9,767
import re, os, sys, subprocess, copy, traceback, logging import requests from . import config def print_line(msg, oneLine = False): if oneLine: sys.stdout.write(' '*40 + '\r') sys.stdout.flush() else: sys.stdout.write('\n') sys.stdout.write(msg.encode(sys.stdin.encoding or 'utf8', '...
null
9,768
import time, re, io import json, copy import logging from .. import config, utils from ..components.contact import accept_friend from ..returnvalues import ReturnValue from ..storage import contact_change from ..utils import update_info_dict def update_chatroom(self, userName, detailedMember=False): if not isinstan...
null
9,769
import os, time, re, io import json import mimetypes, hashlib import logging from collections import OrderedDict from .. import config, utils from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_uin async def send_raw_msg(self, msgType, content, toUserName): url =...
null
9,770
import asyncio import os, time, re, io import threading import json import random import traceback import logging import requests from pyqrcode import QRCode from .. import config, utils from ..returnvalues import ReturnValue from ..storage.templates import wrap_user_dict from .contact import update_local_chatrooms, u...
null
9,771
import logging, traceback, sys, threading from ..log import set_logging from ..utils import test_connect from ..storage import templates async def auto_login(self, EventScanPayload=None,ScanStatus=None,event_stream=None, hotReload=True, statusStorageDir='itchat.pkl', enableCmdQR=False, picDir=None, qrCa...
null
9,772
import pickle, os import logging import requests from ..config import VERSION from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg async def dump_login_status(self, fileDir=None): fileDir = fileDir...
null
9,773
import time import re import io import json import copy import logging from .. import config, utils from ..returnvalues import ReturnValue from ..storage import contact_change from ..utils import update_info_dict def update_chatroom(self, userName, detailedMember=False): if not isinstance(userName, list): u...
null
9,774
import os, time, re, io import json import mimetypes, hashlib import logging from collections import OrderedDict import requests from .. import config, utils from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_uin def send_raw_msg(self, msgType, content, toUserName):...
null
9,775
import os import time import re import io import threading import json import xml.dom.minidom import random import traceback import logging import requests from pyqrcode import QRCode from .. import config, utils from ..returnvalues import ReturnValue from ..storage.templates import wrap_user_dict from .contact import ...
null
9,776
import logging, traceback, sys, threading from ..log import set_logging from ..utils import test_connect from ..storage import templates def auto_login(self, hotReload=False, statusStorageDir='itchat.pkl', enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): if no...
null
9,777
import pickle, os import logging import requests from ..config import VERSION from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg def dump_login_status(self, fileDir=None): def load_login_status(self, ...
null
9,778
import re import time import requests import config from bot.bot import Bot from bot.chatgpt.chat_gpt_session import ChatGPTSession from bot.session_manager import SessionManager from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from common.log import logger from config import co...
null
9,779
from common import const class BaiduWenxinBot(Bot): def __init__(self): super().__init__() wenxin_model = conf().get("baidu_wenxin_model") or "eb-instant" if conf().get("model") and conf().get("model") == "wenxin-4": wenxin_model = "completions_pro" self.sessions = Sess...
create a bot_type instance :param bot_type: bot type code :return: bot instance
9,780
from bot.session_manager import Session from common.log import logger The provided code snippet includes necessary dependencies for implementing the `num_tokens_from_string` function. Write a Python function `def num_tokens_from_string(string: str, model: str) -> int` to solve the following problem: Returns the number...
Returns the number of tokens in a text string.
9,781
from bot.session_manager import Session from common.log import logger from common import const def num_tokens_by_character(messages): """Returns the number of tokens used by a list of messages.""" tokens = 0 for msg in messages: tokens += len(msg["content"]) return tokens = The provided code s...
Returns the number of tokens used by a list of messages.
9,782
from bot.session_manager import Session from common.log import logger The provided code snippet includes necessary dependencies for implementing the `num_tokens_from_messages` function. Write a Python function `def num_tokens_from_messages(messages, model)` to solve the following problem: Returns the number of tokens ...
Returns the number of tokens used by a list of messages.
9,783
import requests, json from bot.bot import Bot from bot.session_manager import SessionManager from bot.baidu.baidu_wenxin_session import BaiduWenxinSession from bridge.context import ContextType, Context from bridge.reply import Reply, ReplyType from common.log import logger from config import conf from common import co...
null
9,784
import requests, json from bot.bot import Bot from bot.session_manager import SessionManager from bot.baidu.baidu_wenxin_session import BaiduWenxinSession from bridge.context import ContextType, Context from bridge.reply import Reply, ReplyType from common.log import logger from config import conf from common import co...
null
9,785
import requests, json from bot.bot import Bot from bot.session_manager import SessionManager from bot.baidu.baidu_wenxin_session import BaiduWenxinSession from bridge.context import ContextType, Context from bridge.reply import Reply, ReplyType from common.log import logger from config import conf from common import co...
null
9,786
import requests, json from bot.bot import Bot from bot.session_manager import SessionManager from bot.baidu.baidu_wenxin_session import BaiduWenxinSession from bridge.context import ContextType, Context from bridge.reply import Reply, ReplyType from common.log import logger from config import conf from common import co...
null
9,787
from bot.session_manager import Session from common.log import logger def num_tokens_from_messages(messages, model): tokens = 0 for msg in messages: tokens += len(msg["content"]) return tokens
null
9,788
from bot.session_manager import Session from common.log import logger The provided code snippet includes necessary dependencies for implementing the `num_tokens_from_messages` function. Write a Python function `def num_tokens_from_messages(messages, model)` to solve the following problem: Returns the number of tokens ...
Returns the number of tokens used by a list of messages.
9,789
import json import logging import os import pickle from common.log import logger 名 会 图 指 def get_root(): def conf(): = def get_appdata_dir(): data_path = os.path.join(get_root(), conf().get("appdata_dir", "")) if not os.path.exists(data_path): ...
null
9,790
import json import logging import os import pickle from common.log import logger 名 会 图 指 def conf(): def subscribe_msg(): trigger_prefix = conf().get("single_chat_prefix", [""])[0] msg = conf().get("subscribe_msg", "") return msg.format(trigge...
null
9,791
import json import logging import os import pickle from common.log import logger 名 会 图 指 plugin_config = {} The provided code snippet includes necessary dependencies for implementing the `write_plugin_config` function. Write a Python function `def write_p...
写入插件全局配置 :param pconf: 全量插件配置
9,792
import json import logging import os import pickle from common.log import logger 名 会 图 指 plugin_config = {} The provided code snippet includes necessary dependencies for implementing the `pconf` function. Write a Python function `def pconf(plugin_name: st...
根据插件名称获取配置 :param plugin_name: 插件名称 :return: 该插件的配置项
9,793
import os import re import threading import time from asyncio import CancelledError from concurrent.futures import Future, ThreadPoolExecutor from concurrent import futures from bridge.context import * from bridge.reply import * from channel.channel import Channel from common.dequeue import Dequeue from common import m...
null
9,794
import os import re import threading import time from asyncio import CancelledError from concurrent.futures import Future, ThreadPoolExecutor from concurrent import futures from bridge.context import * from bridge.reply import * from channel.channel import Channel from common.dequeue import Dequeue from common import m...
null
9,795
import web from wechatpy.crypto import WeChatCrypto from wechatpy.exceptions import InvalidSignatureException from wechatpy.utils import check_signature from config import conf # openai apibase,当use_azure_chatgpt为true时,需要设置对应的api base "open_ai_api_base": "https://api.openai.com/v1", "proxy": "", # openai使用的代理...
null
9,796
import os import time os.environ['ntwork_LOG'] = "ERROR" import ntwork def forever(): try: while True: time.sleep(0.1) except KeyboardInterrupt: ntwork.exit_() os._exit(0)
null
9,797
import datetime import json import os import re import time import pilk from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from ntwork.const import send_type = def get_with_retry(get_func, max_retries=5, delay=5): retries = 0 result = None whi...
null
9,798
import datetime import json import os import re import time import pilk from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from ntwork.const import send_type = def get_room_info(wework, conversation_id): logger.debug(f"传入的 conversation_id: {conversati...
null
9,799
import datetime import json import os import re import time import pilk from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from ntwork.const import send_type = def cdn_download(wework, message, file_name): data = message["data"] aes_key = data["cd...
null
9,800
import datetime import json import os import re import time import pilk from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from ntwork.const import send_type = def c2c_download_and_convert(wework, message, file_name): data = message["data"] aes_ke...
null
9,801
import io import os import random import tempfile import threading import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_message import WeworkMessage from commo...
null
9,802
import io import os import random import tempfile import threading os.environ['ntwork_LOG'] = "ERROR" import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_mess...
null
9,803
import io import os import random import tempfile import threading os.environ['ntwork_LOG'] = "ERROR" import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_mess...
null
9,804
import io import os import random import tempfile import threading import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_message import WeworkMessage from commo...
null
9,805
import io import os import random import tempfile import threading import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_message import WeworkMessage from commo...
null
9,806
import io import os import random import tempfile import threading import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_message import WeworkMessage from commo...
null
9,807
import io import os import random import tempfile import threading import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_message import WeworkMessage from commo...
null
9,808
import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log impor...
null
9,809
import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log impor...
null
9,810
import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log impor...
null
9,811
import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log impor...
null
9,812
import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log impor...
null
9,813
import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log impor...
null
9,814
The provided code snippet includes necessary dependencies for implementing the `get_pcm_from_wav` function. Write a Python function `def get_pcm_from_wav(wav_path)` to solve the following problem: 从 wav 文件中读取 pcm :param wav_path: wav 文件路径 :returns: pcm 数据 Here is the function: def get_pcm_from_wav(wav_path): ""...
从 wav 文件中读取 pcm :param wav_path: wav 文件路径 :returns: pcm 数据
9,815
import shutil import wave from common.log import logger try: import pysilk except ImportError: logger.warn("import pysilk failed, wechaty voice message will not be supported.") from pydub import AudioSegment sil_supports = [8000, 12000, 16000, 24000, 32000, 44100, 48000] t_sil_supports(sample_rate): """ ...
把任意格式转成mp3文件
9,816
import shutil import wave from common.log import logger try: import pysilk except ImportError: logger.warn("import pysilk failed, wechaty voice message will not be supported.") from pydub import AudioSegment sil_supports = [8000, 12000, 16000, 24000, 32000, 44100, 48000] t_sil_supports(sample_rate): """ ...
把任意格式转成wav文件
9,817
import shutil import wave from common.log import logger try: import pysilk except ImportError: logger.warn("import pysilk failed, wechaty voice message will not be supported.") from pydub import AudioSegment sil_supports = [8000, 12000, 16000, 24000, 32000, 44100, 48000] t_sil_supports(sample_rate): """ ...
把任意格式转成sil文件
9,818
import shutil import wave from common.log import logger try: import pysilk except ImportError: logger.warn("import pysilk failed, wechaty voice message will not be supported.") from pydub import AudioSegment sil_supports = [8000, 12000, 16000, 24000, 32000, 44100, 48000] t_sil_supports(sample_rate): """ ...
把任意格式转成amr文件
9,819
The provided code snippet includes necessary dependencies for implementing the `split_audio` function. Write a Python function `def split_audio(file_path, max_segment_length_ms=60000)` to solve the following problem: 分割音频文件 Here is the function: def split_audio(file_path, max_segment_length_ms=60000): """ 分...
分割音频文件
9,820
class BaiduVoice(Voice): def __init__(self): try: curdir = os.path.dirname(__file__) config_path = os.path.join(curdir, "config.json") bconf = None if not os.path.exists(config_path): # 如果没有配置文件,创建本地配置文件 bconf = {"lang": "zh", "ctp": 1, "spd...
create a voice instance :param voice_type: voice type code :return: voice instance
9,821
import json import time import requests import datetime import hashlib import hmac import base64 import urllib.parse import uuid from common.log import logger from common.tmp_dir import TmpDir = class TmpDir(object): """A temporary directory that is deleted when the object is destroyed.""" tmpFilePath = path...
使用阿里云的文本转语音服务将文本转换为语音。 参数: - url (str): 阿里云文本转语音服务的端点URL。 - text (str): 要转换为语音的文本。 - appkey (str): 您的阿里云appkey。 - token (str): 阿里云API的认证令牌。 返回值: - str: 成功时输出音频文件的路径,否则为None。
9,822
import io import os from urllib.parse import urlparse from PIL import Image def split_string_by_utf8_length(string, max_length, max_split=0): encoded = string.encode("utf-8") start, end = 0, 0 result = [] while end < len(encoded): if max_split > 0 and len(result) >= max_split: resul...
null
9,823
import io import os from urllib.parse import urlparse from PIL import Image def get_path_suffix(path): path = urlparse(path).path return os.path.splitext(path)[-1].lstrip('.')
null
9,824
def singleton(cls): instances = {} def get_instance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return get_instance
null
9,825
import time import pip from pip._internal import main as pipmain from common.log import _reset_logger, logger def _reset_logger(log): for handler in log.handlers: handler.close() log.removeHandler(handler) del handler log.handlers.clear() log.propagate = False console_handle = l...
null
9,826
import time import pip from pip._internal import main as pipmain from common.log import _reset_logger, logger def install(package): pipmain(["install", package]) def check_dulwich(): needwait = False for i in range(2): if needwait: time.sleep(3) needwait = False try:...
null
9,827
import hashlib import re import time import config from common.log import logger = def time_checker(f): def _time_checker(self, *args, **kwargs): _config = config.conf() chat_time_module = _config.get("chat_time_module", False) if chat_time_module: chat_start_time = _config.get...
null
9,828
import logging import sys def _reset_logger(log): def _get_logger(): log = logging.getLogger("log") _reset_logger(log) log.setLevel(logging.INFO) return log
null
9,829
from enum import Enum from config import conf from common.log import logger import requests import threading import time from bridge.reply import Reply, ReplyType import asyncio from bridge.context import ContextType from plugins import EventContext, EventAction from .utils import Util = class Reply: def __init__...
null
9,830
from enum import Enum from config import conf from common.log import logger import requests import threading import time from bridge.reply import Reply, ReplyType import asyncio from bridge.context import ContextType from plugins import EventContext, EventAction from .utils import Util def check_prefix(content, prefix...
null
9,831
import plugins from bridge.context import ContextType from bridge.reply import Reply, ReplyType from plugins import * from .midjourney import MJBot from .summary import LinkSummary from bridge import bridge from common.expired_dict import ExpiredDict from common import const import os from .utils import Util class Rep...
null
9,832
import plugins from bridge.context import ContextType from bridge.reply import Reply, ReplyType from plugins import * from .midjourney import MJBot from .summary import LinkSummary from bridge import bridge from common.expired_dict import ExpiredDict from common import const import os from .utils import Util class Rep...
null
9,833
import plugins from bridge.context import ContextType from bridge.reply import Reply, ReplyType from plugins import * from .midjourney import MJBot from .summary import LinkSummary from bridge import bridge from common.expired_dict import ExpiredDict from common import const import os from .utils import Util def _get_...
null
9,834
import plugins from bridge.context import ContextType from bridge.reply import Reply, ReplyType from plugins import * from .midjourney import MJBot from .summary import LinkSummary from bridge import bridge from common.expired_dict import ExpiredDict from common import const import os from .utils import Util def _find_...
null
9,835
import plugins from bridge.context import ContextType from bridge.reply import Reply, ReplyType from plugins import * from .midjourney import MJBot from .summary import LinkSummary from bridge import bridge from common.expired_dict import ExpiredDict from common import const import os from .utils import Util def _find_...
null
9,836
import json import os import random import string import logging from typing import Tuple import bridge.bridge import plugins from bridge.bridge import Bridge from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common import const from config import conf, load_config, global_config fro...
null
9,837
import glob import os import re import subprocess from os.path import basename, splitext, join from setuptools import setup from setuptools.command.install import install The provided code snippet includes necessary dependencies for implementing the `get_packages` function. Write a Python function `def get_packages(ba...
Return all modules used in input-remapper. For example 'inputremapper.gui' or 'inputremapper.injection.mapping_handlers'
9,838
import glob import os import re import subprocess from os.path import basename, splitext, join from setuptools import setup from setuptools.command.install import install PO_FILES = "po/*.po" for po_file in glob.glob(PO_FILES): lang = splitext(basename(po_file))[0] lang_data.append( ( f"/usr...
Build po files into mo/.
9,839
import sys from hashlib import md5 from typing import Optional import evdev def is_service() -> bool: return sys.argv[0].endswith("input-remapper-service")
null
9,840
import sys from hashlib import md5 from typing import Optional import evdev DeviceHash = str The provided code snippet includes necessary dependencies for implementing the `get_device_hash` function. Write a Python function `def get_device_hash(device: evdev.InputDevice) -> DeviceHash` to solve the following problem: ...
get a unique hash for the given device
9,841
from __future__ import annotations import asyncio import copy import math import re from typing import List, Callable, Awaitable, Tuple, Optional, Union, Any from evdev.ecodes import ( ecodes, EV_KEY, EV_REL, REL_X, REL_Y, REL_WHEEL_HI_RES, REL_HWHEEL_HI_RES, REL_WHEEL, REL_HWHEEL, )...
Check if this is a legit variable name. Because they could clash with language features. If the macro is able to be parsed at all due to a problematic choice of a variable name. Allowed examples: "foo", "Foo1234_", "_foo_1234" Not allowed: "1_foo", "foo=blub", "$foo", "foo,1234", "foo()"
9,842
from __future__ import annotations import asyncio import copy import math import re from typing import List, Callable, Awaitable, Tuple, Optional, Union, Any from evdev.ecodes import ( ecodes, EV_KEY, EV_REL, REL_X, REL_Y, REL_WHEEL_HI_RES, REL_HWHEEL_HI_RES, REL_WHEEL, REL_HWHEEL, )...
If the argument is a variable, figure out its value and cast it. Variables are prefixed with `$` in the syntax. Use this just-in-time when you need the actual value of the variable during runtime.
9,843
import inspect import re from typing import Optional, Any from inputremapper.configs.validation_errors import MacroParsingError from inputremapper.injection.macros.macro import Macro, Variable from inputremapper.logger import logger def _parse_recurse( code: str, context, mapping, verbose: bool, mac...
Parse and generate a Macro that can be run as often as you want. Parameters ---------- macro "repeat(3, key(a).wait(10))" "repeat(2, key(a).key(KEY_A)).key(b)" "wait(1000).modify(Shift_L, repeat(2, k(a))).wait(10, 20).key(b)" context : Context, or None for use in Frontend mapping the mapping for the macro, or None for ...
9,844
import re import subprocess from inputremapper.logger import logger def is_numlock_on(): """Get the current state of the numlock.""" try: xset_q = subprocess.check_output( ["xset", "q"], stderr=subprocess.STDOUT, ).decode() num_lock_status = re.search(r"Num Lock:\...
Decorator to reset the numlock to its initial state afterwards.
9,845
from typing import Dict, Union, Tuple, Optional, List import evdev import inputremapper.exceptions import inputremapper.utils from inputremapper.logger import logger DEFAULT_UINPUTS = { # for event codes see linux/input-event-codes.h "keyboard": { evdev.ecodes.EV_KEY: list(evdev.ecodes.KEY.keys() & evde...
Check if the uinput with the target name is capable of the event.
9,846
from typing import Dict, Union, Tuple, Optional, List import evdev import inputremapper.exceptions import inputremapper.utils from inputremapper.logger import logger DEFAULT_UINPUTS = { # for event codes see linux/input-event-codes.h "keyboard": { evdev.ecodes.EV_KEY: list(evdev.ecodes.KEY.keys() & evde...
Find the names of default uinputs that are able to emit this event.
9,847
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