crossfile_context_retrievalwref
dict
prompt
stringlengths
252
32.6k
right_context
stringlengths
0
81.2k
metadata
dict
crossfile_context_retrieval
dict
groundtruth
stringlengths
5
208
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/backend/common/api_generic.py", "retrieved_chunk": " else:\n msg = \"body is empty!\"\n logger.debug(msg)\n return False, msg\n @staticmethod\n def get_properties():\n \"\"\"Get toolkit pro...
from flask import Flask from flask import jsonify from flask import request from ansys.aedt.toolkits.template.backend.api import Toolkit from ansys.aedt.toolkits.template.backend.common.logger_handler import logger service = Toolkit() settings = service.get_properties() app = Flask(__name__) # Generic services @...
if response: return jsonify("Project saved: {}".format(body)), 200 else: return jsonify(response), 500 @app.route("/get_design_names", methods=["GET"]) def get_design_names_call(): logger.info("[GET] /get_design_names (aedt designs for specific project)") response = service.get_desi...
{ "context_start_lineno": 0, "file": "src/ansys/aedt/toolkits/template/backend/common/rest_api_generic.py", "groundtruth_start_lineno": 138, "repository": "ansys-pyaedt-toolkit-template-73b2fc9", "right_context_start_lineno": 139, "task_id": "project_cc_python/8174" }
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/backend/common/api_generic.py", "retrieved_chunk": " The dictionary containing the toolkit properties.\n Examples\n --------\n >>> from ansys.aedt.toolkits.template.backend.api import Toolkit\n >>> toolk...
save_project(body)
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/backend/common/api_generic.py", "retrieved_chunk": " else:\n msg = \"body is empty!\"\n logger.debug(msg)\n return False, msg\n @staticmethod\n def get_properties():\n \"\"\"Get toolkit pro...
from flask import Flask from flask import jsonify from flask import request from ansys.aedt.toolkits.template.backend.api import Toolkit from ansys.aedt.toolkits.template.backend.common.logger_handler import logger service = Toolkit() settings = service.get_properties() app = Flask(__name__) # Generic services @...
if response: return jsonify("Design connected"), 200 else: return jsonify("Fail to connect to the design"), 500 @app.route("/save_project", methods=["POST"]) def save_project_call(): logger.info("[POST] /save_project (Save AEDT project)") body = request.json if not body: ...
{ "context_start_lineno": 0, "file": "src/ansys/aedt/toolkits/template/backend/common/rest_api_generic.py", "groundtruth_start_lineno": 119, "repository": "ansys-pyaedt-toolkit-template-73b2fc9", "right_context_start_lineno": 120, "task_id": "project_cc_python/8173" }
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/backend/common/api_generic.py", "retrieved_chunk": " The dictionary containing the toolkit properties.\n Examples\n --------\n >>> from ansys.aedt.toolkits.template.backend.api import Toolkit\n >>> toolk...
connect_design(body["aedtapp"])
{ "list": [ { "filename": "tests/conftest.py", "retrieved_chunk": "@pytest.fixture(scope=\"session\", autouse=True)\ndef desktop_init():\n if is_linux:\n initial_pids = psutil.pids()\n else:\n initial_pids = psutil.Process().children(recursive=True)\n # Define the command to sta...
import atexit import json import os import signal import sys import threading import time import psutil import requests from ansys.aedt.toolkits.template import backend from ansys.aedt.toolkits.template import ui with open(os.path.join(os.path.dirname(__file__), "ui", "common", "general_properties.json")) as fh: ...
frontend_command = [python_path, frontend_file] # Clean up python processes def clean_python_processes(): # Terminate backend processes if is_linux: for process in flask_pids: os.kill(process, signal.SIGKILL) else: for process in flask_pids: if process.name() == "p...
{ "context_start_lineno": 0, "file": "src/ansys/aedt/toolkits/template/run_toolkit.py", "groundtruth_start_lineno": 34, "repository": "ansys-pyaedt-toolkit-template-73b2fc9", "right_context_start_lineno": 35, "task_id": "project_cc_python/8161" }
{ "list": [ { "filename": "tests/conftest.py", "retrieved_chunk": " flask_thread = threading.Thread(target=run_command, args=backend_command)\n flask_thread.daemon = True\n flask_thread.start()\n time.sleep(1)\n if is_linux:\n current_process = len(psutil.pids())\n count =...
__path__[0], "frontend_actions.py")
{ "list": [ { "filename": "bumpversion/version_part.py", "retrieved_chunk": " self.config = config\n self.func: Optional[PartFunction] = None\n if config.values:\n self.func = ValuesFunction(config.values, config.optional_value, config.first_value)\n else:\n ...
import pytest from bumpversion.functions import NumericFunction, ValuesFunction # NumericFunction def test_numeric_init_wo_first_value(): func = NumericFunction() assert func.first_value == "0" def test_numeric_init_w_first_value(): func = NumericFunction(first_value="5") assert func.first_value =...
def test_numeric_bump_prefix_and_suffix(): func = NumericFunction() assert func.bump("v0b") == "v1b" # ValuesFunction def test_values_init(): func = ValuesFunction(["0", "1", "2"]) assert func.optional_value == "0" assert func.first_value == "0" def test_values_init_w_correct_optional_value...
{ "context_start_lineno": 0, "file": "tests/test_functions.py", "groundtruth_start_lineno": 24, "repository": "callowayproject-bump-my-version-0cf1cb5", "right_context_start_lineno": 25, "task_id": "project_cc_python/8156" }
{ "list": [ { "filename": "bumpversion/version_part.py", "retrieved_chunk": " def copy(self) -> \"VersionPart\":\n \"\"\"Return a copy of the part.\"\"\"\n return VersionPart(self.config, self._value)\n def bump(self) -> \"VersionPart\":\n \"\"\"Return a part with bumped val...
bump("0") == "1"
{ "list": [ { "filename": "bumpversion/version_part.py", "retrieved_chunk": " self.config = config\n self.func: Optional[PartFunction] = None\n if config.values:\n self.func = ValuesFunction(config.values, config.optional_value, config.first_value)\n else:\n ...
import pytest from bumpversion.functions import NumericFunction, ValuesFunction # NumericFunction def test_numeric_init_wo_first_value(): func = NumericFunction() assert func.first_value == "0" def test_numeric_init_w_first_value(): func = NumericFunction(first_value="5") assert func.first_value =...
assert func.first_value == "0" def test_values_init_w_correct_optional_value(): func = ValuesFunction(["0", "1", "2"], optional_value="1") assert func.optional_value == "1" assert func.first_value == "0" def test_values_init_w_correct_first_value(): func = ValuesFunction(["0", "1", "2"], first_...
{ "context_start_lineno": 0, "file": "tests/test_functions.py", "groundtruth_start_lineno": 37, "repository": "callowayproject-bump-my-version-0cf1cb5", "right_context_start_lineno": 38, "task_id": "project_cc_python/8157" }
{ "list": [ { "filename": "bumpversion/version_part.py", "retrieved_chunk": " def copy(self) -> \"VersionPart\":\n \"\"\"Return a copy of the part.\"\"\"\n return VersionPart(self.config, self._value)\n def bump(self) -> \"VersionPart\":\n \"\"\"Return a part with bumped val...
optional_value == "0"
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/backend/api.py", "retrieved_chunk": " \"\"\"\n # Connect to AEDT design\n self.connect_design()\n if self.aedtapp:\n multiplier = properties.multiplier\n geometry = properties.geometry\n ...
import os import requests from ansys.aedt.toolkits.template.ui.common.frontend_api_generic import FrontendGeneric from ansys.aedt.toolkits.template.ui.common.logger_handler import logger from ansys.aedt.toolkits.template.ui.common.thread_manager import FrontendThread class ToolkitFrontend(FrontendThread, FrontendGe...
project_selected = self.project_aedt_combo.currentText() for project in properties["project_list"]: if os.path.splitext(os.path.basename(project))[0] == project_selected and project_selected != "No project": properties["active_project"] = project design_selec...
{ "context_start_lineno": 0, "file": "src/ansys/aedt/toolkits/template/ui/frontend_api.py", "groundtruth_start_lineno": 23, "repository": "ansys-pyaedt-toolkit-template-73b2fc9", "right_context_start_lineno": 24, "task_id": "project_cc_python/8181" }
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/backend/api.py", "retrieved_chunk": " self.draw_sphere()\n self.aedtapp.release_desktop(False, False)\n self.aedtapp = None\n return True\n return False\n def draw_box(self):\n ...
geometry_combo.currentText()
{ "list": [ { "filename": "bumpversion/version_part.py", "retrieved_chunk": " self.config = config\n self.func: Optional[PartFunction] = None\n if config.values:\n self.func = ValuesFunction(config.values, config.optional_value, config.first_value)\n else:\n ...
import pytest from bumpversion.functions import NumericFunction, ValuesFunction # NumericFunction def test_numeric_init_wo_first_value(): func = NumericFunction() assert func.first_value == "0" def test_numeric_init_w_first_value(): func = NumericFunction(first_value="5") assert func.first_value =...
def test_values_init_w_correct_optional_value(): func = ValuesFunction(["0", "1", "2"], optional_value="1") assert func.optional_value == "1" assert func.first_value == "0" def test_values_init_w_correct_first_value(): func = ValuesFunction(["0", "1", "2"], first_value="1") assert func.optional...
{ "context_start_lineno": 0, "file": "tests/test_functions.py", "groundtruth_start_lineno": 38, "repository": "callowayproject-bump-my-version-0cf1cb5", "right_context_start_lineno": 39, "task_id": "project_cc_python/8158" }
{ "list": [ { "filename": "bumpversion/version_part.py", "retrieved_chunk": " def copy(self) -> \"VersionPart\":\n \"\"\"Return a copy of the part.\"\"\"\n return VersionPart(self.config, self._value)\n def bump(self) -> \"VersionPart\":\n \"\"\"Return a part with bumped val...
first_value == "0"
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/run_toolkit.py", "retrieved_chunk": "from ansys.aedt.toolkits.template import ui\nwith open(os.path.join(os.path.dirname(__file__), \"ui\", \"common\", \"general_properties.json\")) as fh:\n general_settings = json.load(fh)\nurl = general_...
import json import os import sys from PySide6 import QtWidgets from ansys.aedt.toolkits.template.ui.common.frontend_ui import Ui_MainWindow from ansys.aedt.toolkits.template.ui.common.logger_handler import logger from ansys.aedt.toolkits.template.ui.frontend_api import ToolkitFrontend os.environ["QT_API"] = "pyside6...
super(ApplicationWindow, self).__init__() ToolkitFrontend.__init__(self) self.url = "http://" + url + ":" + port # Set title self.set_title(toolkit_title) # Check backend connection self.backend = self.check_connection() if not self.backend: ...
{ "context_start_lineno": 0, "file": "src/ansys/aedt/toolkits/template/ui/frontend_actions.py", "groundtruth_start_lineno": 26, "repository": "ansys-pyaedt-toolkit-template-73b2fc9", "right_context_start_lineno": 27, "task_id": "project_cc_python/8188" }
{ "list": [ { "filename": "src/ansys/aedt/toolkits/template/run_toolkit.py", "retrieved_chunk": "# Define the command to start the Flask application\nbackend_file = os.path.join(backend.__path__[0], \"rest_api.py\")\nbackend_command = [python_path, backend_file]\n# Define the command to start the PySi...
info("Frontend initialization...")
{ "list": [ { "filename": "shell_craft/configuration.py", "retrieved_chunk": "import json\nfrom typing import Any, Protocol\nimport pathlib\nclass Configuration(Protocol):\n def get(self, key: Any, default=None) -> Any:\n ...\nclass JSONConfiguration(dict):\n def __init__(self, text: str)...
# Copyright (c) 2023 Johnathan P. Irvin and contributors # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify,...
def test_aggregate_from_files() -> None: with patch("builtins.open", mock_open(read_data="""{ "key": "json" }""")): with patch("pathlib.Path.exists", return_value=True): assert AggregateConfiguration.from_files(["file.json"]).get("key") == "json"
{ "context_start_lineno": 0, "file": "tests/test_configuration.py", "groundtruth_start_lineno": 69, "repository": "JohnnyIrvin-shell-craft-26a7af7", "right_context_start_lineno": 70, "task_id": "project_cc_python/8245" }
{ "list": [ { "filename": "shell_craft/configuration.py", "retrieved_chunk": " Initialize the aggregate configuration from the given files.\n If a file does not exist, it will be ignored.\n Args:\n paths (list[str]): The paths to the JSON files.\n Returns:\n ...
from_file("file.json").get("key") == "json"
{ "list": [ { "filename": "shell_craft/cli/main.py", "retrieved_chunk": " prompt = PromptFactory.get_prompt(args.prompt)\n if getattr(args, \"refactor\", False):\n prompt = prompt.refactoring\n elif getattr(args, \"document\", False):\n prompt = prompt.documentation\n elif ge...
# Copyright (c) 2023 Johnathan P. Irvin and contributors # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify,...
{ "context_start_lineno": 0, "file": "tests/test_factories.py", "groundtruth_start_lineno": 40, "repository": "JohnnyIrvin-shell-craft-26a7af7", "right_context_start_lineno": 41, "task_id": "project_cc_python/8244" }
{ "list": [ { "filename": "shell_craft/factories/prompt.py", "retrieved_chunk": " ValueError: If the prompt type is not supported.\n Returns:\n Prompt: A new prompt object.\n \"\"\" \n import shell_craft.prompts as prompts\n if not prompt:\n ...
get_prompt(prompt.removesuffix("_PROMPT")) == getattr(prompts, prompt)
{ "list": [ { "filename": "shell_craft/cli/main.py", "retrieved_chunk": " prompt = PromptFactory.get_prompt(args.prompt)\n if getattr(args, \"refactor\", False):\n prompt = prompt.refactoring\n elif getattr(args, \"document\", False):\n prompt = prompt.documentation\n elif ge...
# Copyright (c) 2023 Johnathan P. Irvin and contributors # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify,...
for restriction in command.restrictions: if restriction == CommandRestriction.PROMPT_TYPE: if type(prompt).__name__ in command.restrictions[restriction]: continue if restriction == CommandRestriction.PROMPT_NAME: prompt_name ...
{ "context_start_lineno": 0, "file": "shell_craft/cli/parser.py", "groundtruth_start_lineno": 125, "repository": "JohnnyIrvin-shell-craft-26a7af7", "right_context_start_lineno": 126, "task_id": "project_cc_python/8247" }
{ "list": [ { "filename": "shell_craft/cli/main.py", "retrieved_chunk": " model=args.model,\n count=args.count,\n temperature=args.temperature,\n messages=prompt.messages,\n )\n ).query(\n message=' '.join(args.request),\n )\n github_u...
get_prompt(known_args.prompt)
{ "list": [ { "filename": "parser/LangParserListener.py", "retrieved_chunk": " func_return_type, func_name = None, None\n func_name = str(function_ctxt.children[0])\n if isinstance(function_ctxt, LangParser.CustFuncCallContext):\n find_name = self.function_vars.get(func...
from antlr4.error.Errors import RecognitionException, NoViableAltException, InputMismatchException, \ FailedPredicateException from antlr4.error.ErrorStrategy import DefaultErrorStrategy from antlr4 import * from parser.LangParser import LangParser class MyErrorStrategy(DefaultErrorStrategy): def __init__(sel...
msg = "create function has a different form - {}. Expected create_function(params)." elif isinstance(localctx, LangParser.DelFuncContext): msg = "delete function has a mismatched form - {}. Expected delete_function(params)." elif isinstance(localctx, LangParser.InsertStmtContext...
{ "context_start_lineno": 0, "file": "MyErrorStrategy.py", "groundtruth_start_lineno": 58, "repository": "eugenos-programos-Own-language-with-LLVM-lite-c8b9e08", "right_context_start_lineno": 59, "task_id": "project_cc_python/8298" }
{ "list": [ { "filename": "parser/LangParserListener.py", "retrieved_chunk": " if expr.basicType().ID():\n return self.global_vars.get(str(expr.basicType().ID()))\n elif expr.basicType().NUMBER():\n value = float(str(expr.basicType()....
CreateTablStmtContext)):
{ "list": [ { "filename": "parser/LangParserListener.py", "retrieved_chunk": " func_return_type, func_name = None, None\n func_name = str(function_ctxt.children[0])\n if isinstance(function_ctxt, LangParser.CustFuncCallContext):\n find_name = self.function_vars.get(func...
from antlr4.error.Errors import RecognitionException, NoViableAltException, InputMismatchException, \ FailedPredicateException from antlr4.error.ErrorStrategy import DefaultErrorStrategy from antlr4 import * from parser.LangParser import LangParser class MyErrorStrategy(DefaultErrorStrategy): def __init__(sel...
msg = "create function has a different form - {}. Expected create_function(params)." elif isinstance(localctx, LangParser.DelFuncContext): msg = "delete function has a mismatched form - {}. Expected delete_function(params)." elif isinstance(localctx, LangParser.InsertStmtContext...
{ "context_start_lineno": 0, "file": "MyErrorStrategy.py", "groundtruth_start_lineno": 58, "repository": "eugenos-programos-Own-language-with-LLVM-lite-c8b9e08", "right_context_start_lineno": 59, "task_id": "project_cc_python/8297" }
{ "list": [ { "filename": "parser/LangParserListener.py", "retrieved_chunk": " if expr.basicType().ID():\n return self.global_vars.get(str(expr.basicType().ID()))\n elif expr.basicType().NUMBER():\n value = float(str(expr.basicType()....
CreateRowStmtContext, LangParser.CreateTablStmtContext)):
{ "list": [ { "filename": "parser/LangParserListener.py", "retrieved_chunk": " func_return_type, func_name = None, None\n func_name = str(function_ctxt.children[0])\n if isinstance(function_ctxt, LangParser.CustFuncCallContext):\n find_name = self.function_vars.get(func...
from antlr4.error.Errors import RecognitionException, NoViableAltException, InputMismatchException, \ FailedPredicateException from antlr4.error.ErrorStrategy import DefaultErrorStrategy from antlr4 import * from parser.LangParser import LangParser class MyErrorStrategy(DefaultErrorStrategy): def __init__(sel...
msg = "create function has a different form - {}. Expected create_function(params)." elif isinstance(localctx, LangParser.DelFuncContext): msg = "delete function has a mismatched form - {}. Expected delete_function(params)." elif isinstance(localctx, LangParser.InsertStmtContext...
{ "context_start_lineno": 0, "file": "MyErrorStrategy.py", "groundtruth_start_lineno": 58, "repository": "eugenos-programos-Own-language-with-LLVM-lite-c8b9e08", "right_context_start_lineno": 59, "task_id": "project_cc_python/8296" }
{ "list": [ { "filename": "parser/LangParserListener.py", "retrieved_chunk": " if not isinstance(value, StringVariable):\n self.global_vars[str_name] = StringVariable(value, self.program_compiler._builder)\n else:\n self.global_vars[str_name] = value...
CreateColStmtContext, LangParser.CreateRowStmtContext, LangParser.CreateTablStmtContext)):
{ "list": [ { "filename": "src/variables/NumbVariable.py", "retrieved_chunk": " value\n )\n elif isinstance(value, ir.instructions.Instruction):\n self.var = value\n else:\n self.var = self.builder.load(value.ptr)\n self.ptr = self.b...
from llvmlite import ir from src.IterVariable import IterVariable from basic_types import iter class RowVariable(IterVariable): def __init__(self, elements: tuple = None, builder: ir.builder.IRBuilder = None, ptr=None) -> None: super().__init__(elements, len(elements), builder, ptr) def set_value(se...
{ "context_start_lineno": 0, "file": "src/RowVariable.py", "groundtruth_start_lineno": 23, "repository": "eugenos-programos-Own-language-with-LLVM-lite-c8b9e08", "right_context_start_lineno": 24, "task_id": "project_cc_python/8312" }
{ "list": [ { "filename": "src/variables/IterVariable.py", "retrieved_chunk": " self.var = value.var\n self.size = value.size\n self.ptr = value.ptr\n def get_value(self):\n return self.ptr", "score": 103.39071884547549 }, { "filename": "src/variables...
builder.insert_value(self.ptr, value, index)
{ "list": [ { "filename": "experiments/experiments.py", "retrieved_chunk": " u_test = quad.cs_u_from_v(z=z_test, v=v_test_real)['u'].toarray()\n ref_gp_ins = torch.from_numpy(np.vstack((z_test, u_test))).T\n delv_pred, u_cov, preds = gp_inv.predict(ref_gp_ins)\n v_test_prior = quad_prior.c...
import seaborn as sns sns.set(style="whitegrid") import numpy as np import torch import gpytorch import munch import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from quad_1D.quad_1d import Quad1D from learning.gp_utils import ZeroMeanAffineGP, GaussianProcess, train_gp from utils.plo...
delv_pred2, u_cov2, preds2 = gp2.predict(ref_gp_ins) v_pred2 = delv_pred2.T plot_trained_gp(v_test_real, v_pred2, preds2, fig_count=figcount, show=True)
{ "context_start_lineno": 0, "file": "testing/testing_LHS_train.py", "groundtruth_start_lineno": 99, "repository": "utiasDSL-fmpc_socp-de13764", "right_context_start_lineno": 100, "task_id": "project_cc_python/8226" }
{ "list": [ { "filename": "experiments/experiments.py", "retrieved_chunk": " delv_pred2, u_cov2, preds2 = gp2.predict(ref_gp_ins)\n v_pred2 = delv_pred2.T\n plot_trained_gp(v_test_real, v_pred2, preds2, fig_count=figcount, show=True)\n return gp2\ndef train_gpmpc_gp(config, quad, quad_prio...
init_with_hyperparam(config.output_dir)
{ "list": [ { "filename": "quad_1D/gp_utils.py", "retrieved_chunk": " mean_x = self.mean_module(x) # is this needed for ZeroMean?\n covar_x = self.covar_module(x)\n return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n def compute_gammas(self, query):\n ret...
import torch import gpytorch import numpy as np import matplotlib.pyplot as plt from learning.gp_utils import GaussianProcess, ConstantMeanAffineGP N = 200 x_max = 2 x_min = 0 x_delta = x_max*0.1 # Make training data train_z = torch.linspace(x_min, x_max, N).double() train_u = torch.linspace(x_min, x_max,N).double() ...
# plot gamma computed means plt.fill_between(test_x.numpy()[:,0], lower.numpy(), upper.numpy(), alpha=0.5, label='95%') plt.fill_between(test_x.numpy()[:,0], lower_from_gamma[:,0].numpy(), upper_from_gamma[:,0].numpy(), alpha=0.5, label='95% from gammas') plt.plot(test_x.numpy()[:,0],means,'r', label='GP Mean') plt.pl...
{ "context_start_lineno": 0, "file": "testing/testing_gps.py", "groundtruth_start_lineno": 41, "repository": "utiasDSL-fmpc_socp-de13764", "right_context_start_lineno": 42, "task_id": "project_cc_python/8229" }
{ "list": [ { "filename": "quad_1D/gp_utils.py", "retrieved_chunk": " upper_from_gamma = means_from_gamma + covs_from_gamma.sqrt() * 2\n lower_from_gamma = means_from_gamma - covs_from_gamma.sqrt() * 2\n return means_from_gamma, covs_from_gamma, upper_from_gamma, lower_from_gamma\...
model.mean_and_cov_from_gammas(test_x)
{ "list": [ { "filename": "testing/testing_exp_mpc.py", "retrieved_chunk": "Thrust = 10 # Thrust\ntau = 0.2 # Time constant\ngamma = 3 # Drag\nref_type = 'step'\n# Define 2d quadrotor and reference traj\nquad = Quad1D(T=Thrust, tau=tau, gamma=gamma, dt=dt, ref_type=ref_type)\nT_prior = 7.0 # Thrust\nt...
from sympy import * import numpy as np from quad_1D.quad_1d import Quad1D import matplotlib.pyplot as plt init_printing(use_unicode=True) t, delta_t, omega, amp = symbols('t delta_t omega amp') z_0 = amp*(0.5 + 0.5*tanh((t-delta_t)*omega)) z_1 = diff(z_0, t) z_2 = diff(z_1, t) v_ref = diff(z_2,t) pprint('z_0:') pprint...
{ "context_start_lineno": 0, "file": "symbolics/step_traj_approx.py", "groundtruth_start_lineno": 29, "repository": "utiasDSL-fmpc_socp-de13764", "right_context_start_lineno": 30, "task_id": "project_cc_python/8235" }
{ "list": [ { "filename": "testing/testing_socp_dlqr.py", "retrieved_chunk": " q_lqr=q_lqr,\n r_lqr=r_lqr)\n#dlqr = DLQR(quad=quad,\n# horizon=horizon,\n# dt=dt,\n# q_lqr=q_lqr,\n# r_lqr=r_lqr)\n# Reference\nAmp = 0.2\nomega = 0.8", ...
reference_generator(t, Amp, omega, ref_type='step')
{ "list": [ { "filename": "lm_benchmark/models/positional_encoders/rotary.py", "retrieved_chunk": " self.max_pos_base = 10 \n n_embd_per_head = config.n_embd // config.n_head\n freqs = (self.max_pos_base ** (-self.max_pos_log * torch.arange(0, n_embd_per_head, 2)[:(n_embd_per_he...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
#assert self.config.mem_freq is not None is_mem = (x == self.config.landmark_id) jumps = torch.cumsum((is_mem * torch.randint_like(x, self.config.pos_jump_on_mem))[:, :-1], dim=-1) return x, self.closure_model(self, jumps.unsqueeze(1)) # (B, 1, T) else: ...
{ "context_start_lineno": 0, "file": "lm_benchmark/models/positional_encoders/rotary_mem_jump.py", "groundtruth_start_lineno": 67, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 68, "task_id": "project_cc_python/8261" }
{ "list": [ { "filename": "lm_benchmark/models/positional_encoders/rotary.py", "retrieved_chunk": " self.max_pos_base = 10 \n n_embd_per_head = config.n_embd // config.n_head\n freqs = (self.max_pos_base ** (-self.max_pos_log * torch.arange(0, n_embd_per_head, 2)[:(n_embd_per_he...
config.pos_jump_on_mem is not None and self.config.pos_jump_on_mem > 0:
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "from optim.utils import get_batch\ndef get_args():\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--checkpoint', type=str, required=True)\n args, rem_args = parser.parse_known_args()\n if o...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def main(args): torch.backends.cuda.matmul.allow_tf32 = True # allows us to make sure we're able to use tensorfloat32 during training torch.backends.cudnn.allow_tf32 = True distributed_backend = distributed.make_backend_from_args(args) args = distributed_backend.get_adjusted_args_for_process(args...
{ "context_start_lineno": 0, "file": "lm_benchmark/main.py", "groundtruth_start_lineno": 39, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 40, "task_id": "project_cc_python/8251" }
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "from optim.utils import get_batch\ndef get_args():\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--checkpoint', type=str, required=True)\n args, rem_args = parser.parse_known_args()\n if o...
parse_args_with_format(format=args.config_format, base_parser=parser, args=rem_args, namespace=args)
{ "list": [ { "filename": "lm_benchmark/main.py", "retrieved_chunk": " parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--config_format', default='base', choices=config.registered_formats())\n args, rem_args = parser.parse_known_args()\n return config.parse_args_...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def get_as_batch(data, seq_length, batch_size, device='cpu', sample_size=None): all_ix = list(range(0, len(data), seq_length)) assert all_ix[-1] + seq_length + 1 > len(data) all_ix.pop() if sample_size is not None: all_ix = np.random.choice(all_ix, size=sample_size // seq_length, replace=Fals...
{ "context_start_lineno": 0, "file": "lm_benchmark/eval.py", "groundtruth_start_lineno": 55, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 56, "task_id": "project_cc_python/8254" }
{ "list": [ { "filename": "lm_benchmark/main.py", "retrieved_chunk": " train = train_xl\n else: \n train = train_base\n print(f\"\\nTraining model={args.model} \\n{vars(args)}\\n\")\n stats = train(model, opt, data, scheduler, args.iterations, args.acc_steps, args.batch_size, ar...
parse_args_with_format(format=args.config_format, base_parser=argparse.ArgumentParser(allow_abbrev=False), args=rem_args, namespace=args)
{ "list": [ { "filename": "lm_benchmark/models/caches/kv_cache_train.py", "retrieved_chunk": " k_indices = torch.cat((\n torch.arange(self.cache_size - self.cache_iter, self.cache_size, device=q.device),\n torch.arange(self.cache_size - cached_keys.shape[2], self.cache_siz...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
return att_incomplete, {'v': last_incomplete_v.clone(), 'is_mem': last_incomplete_mem.clone()} top_k = self.config.cache_topk k_with_cached_mem = self.cache_mem_k[:B, :self.cache_size, -1].view(B, -1, nh, hs).transpose(1, 2) # (B, nh, T, hs) mem_indices = torch.cat(( ...
{ "context_start_lineno": 0, "file": "lm_benchmark/models/caches/mem_cache.py", "groundtruth_start_lineno": 47, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 48, "task_id": "project_cc_python/8268" }
{ "list": [ { "filename": "lm_benchmark/models/caches/kv_cache_train.py", "retrieved_chunk": " if self.max_cache_size == 0:\n return\n B, nh, T, hs = keys.size()\n k_for_cache = keys[:, :, -self.max_cache_size:]\n v_for_cache = values_dict['v'][:, :, -self.max_ca...
config.cache_topk == 0:
{ "list": [ { "filename": "lm_benchmark/models/caches/kv_cache_train.py", "retrieved_chunk": " k_indices = torch.cat((\n torch.arange(self.cache_size - self.cache_iter, self.cache_size, device=q.device),\n torch.arange(self.cache_size - cached_keys.shape[2], self.cache_siz...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
if self.cache_size == 0 or self.config.cache_topk == 0: return att_incomplete, {'v': last_incomplete_v.clone(), 'is_mem': last_incomplete_mem.clone()} top_k = self.config.cache_topk k_with_cached_mem = self.cache_mem_k[:B, :self.cache_size, -1].view(B, -1, nh, hs).transpos...
{ "context_start_lineno": 0, "file": "lm_benchmark/models/caches/mem_cache.py", "groundtruth_start_lineno": 45, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 46, "task_id": "project_cc_python/8267" }
{ "list": [ { "filename": "lm_benchmark/models/caches/kv_cache_train.py", "retrieved_chunk": " if self.max_cache_size == 0:\n return\n B, nh, T, hs = keys.size()\n k_for_cache = keys[:, :, -self.max_cache_size:]\n v_for_cache = values_dict['v'][:, :, -self.max_ca...
last_incomplete_ismem[:B, :self.last_incomplete_len]
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "from optim.utils import get_batch\ndef get_args():\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--checkpoint', type=str, required=True)\n args, rem_args = parser.parse_known_args()\n if o...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# logging params (WandB) parser.add_argument('--wandb', action='store_true') # whether to use wandb or not parser.add_argument('--wandb_project', default="my-project", type=str) # Distributed args parser.add_argument('--distributed_backend', default=None, type=none_or_str, required=False, ...
{ "context_start_lineno": 0, "file": "lm_benchmark/config/rotary.py", "groundtruth_start_lineno": 74, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 75, "task_id": "project_cc_python/8280" }
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": " summary = json.load(f)\n for k, v in summary['args'].items():\n if k not in [\"device\", \"dtype\"]:\n setattr(args, k, v)\n return config.parse_args_with_format(format=args.config_format, base_parser...
positional_encoders.registered_encoders()) # distributed backend type
{ "list": [ { "filename": "lm_benchmark/models/caches/kv_cache_train.py", "retrieved_chunk": " def cache_v(self):\n return self._cache_v[0]\n def clear_state(self):\n self.cache_iter = 0\n self.cache_size = 0\n def retrieve_for_query(self, q, cache_context, pos_emb_closur...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
att_incomplete = (q @ last_incomplete_k.transpose(-2, -1)) * (1.0 / math.sqrt(last_incomplete_k.size(-1))) last_incomplete_v = self.last_incomplete_v[:B, :, :self.last_incomplete_len].unsqueeze(2).expand(B, nh, T, self.last_incomplete_len, hs) last_incomplete_mem = self.last_incomplete_ismem[:B...
{ "context_start_lineno": 0, "file": "lm_benchmark/models/caches/mem_cache.py", "groundtruth_start_lineno": 42, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 43, "task_id": "project_cc_python/8265" }
{ "list": [ { "filename": "lm_benchmark/models/caches/kv_cache_train.py", "retrieved_chunk": " k_indices = torch.cat((\n torch.arange(self.cache_size - self.cache_iter, self.cache_size, device=q.device),\n torch.arange(self.cache_size - cached_keys.shape[2], self.cache_siz...
last_incomplete_k[:B, :, :self.last_incomplete_len], start_index=start_index - self.last_incomplete_len)
{ "list": [ { "filename": "lm_benchmark/models/landmark_with_cmt.py", "retrieved_chunk": " return\n print(\"Init Storage\")\n self.cache_storage = lm_cache.get_storage_for_layer(self)\n def forward(self, x, is_mem, pos_emb_closure, cache_context, start_index):\n B, T...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
full_len = T - incomplete_len mem_x, incomplete_x = torch.split(x, (full_len, incomplete_len), dim=-1) mem_x = mem_x.view(B, -1, self.config.mem_cache_freq) mem_x = torch.cat((mem_x, mem_x.new_full((mem_x.shape[0], mem_x.shape[1], 1), self.config.landmark_id)), dim=-1) x = torch...
{ "context_start_lineno": 0, "file": "lm_benchmark/models/caches/mem_cache.py", "groundtruth_start_lineno": 187, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 188, "task_id": "project_cc_python/8271" }
{ "list": [ { "filename": "lm_benchmark/models/landmark_with_cmt.py", "retrieved_chunk": " rem_token_embedding = k[:, :, 0].unsqueeze(2)\n q = q[:, :, 1:]\n k = k[:, :, 1:]\n v = v[:, :, 1:]\n T -= 1\n q = pos_emb_closure.adapt_queries(q, start_index=start_ind...
config.mem_cache_freq
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "import argparse\nimport random\nimport wandb\nimport logging\nfrom tqdm import tqdm\nimport config\nimport models\nfrom data import get_dataset, prepare_dataset\nfrom optim.base import train_base\nimport distributed", "score":...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
args, rem_args = parser.parse_known_args() return config.parse_args_with_format(format=args.config_format, base_parser=parser, args=rem_args, namespace=args) def main(args): torch.backends.cuda.matmul.allow_tf32 = True # allows us to make sure we're able to use tensorfloat32 during training torc...
{ "context_start_lineno": 0, "file": "lm_benchmark/main.py", "groundtruth_start_lineno": 35, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 36, "task_id": "project_cc_python/8250" }
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "from optim.utils import get_batch\ndef get_args():\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--checkpoint', type=str, required=True)\n args, rem_args = parser.parse_known_args()\n if o...
registered_formats())
{ "list": [ { "filename": "trainer/tasks/base_task.py", "retrieved_chunk": " def evaluate(self, model, criterion, dataloader):\n pass\n def log_to_wandb(self, eval_dict, table_name=\"test_predictions\"):\n if not self.accelerator.is_main_process or not LoggerType.WANDB == self.acce...
import collections from dataclasses import dataclass import torch from PIL import Image from accelerate.logging import get_logger from accelerate.utils import LoggerType from omegaconf import II from transformers import AutoTokenizer from trainer.accelerators.base_accelerator import BaseAccelerator from trainer.tasks...
metrics = { "accuracy": sum(eval_dict["is_correct"]) / len(eval_dict["is_correct"]), "num_samples": len(eval_dict["is_correct"]) } if LoggerType.WANDB == self.accelerator.cfg.log_with: self.log_to_wandb(eval_dict) return metrics
{ "context_start_lineno": 0, "file": "trainer/tasks/clip_task.py", "groundtruth_start_lineno": 98, "repository": "yuvalkirstain-PickScore-5fa69e8", "right_context_start_lineno": 99, "task_id": "project_cc_python/8322" }
{ "list": [ { "filename": "trainer/tasks/base_task.py", "retrieved_chunk": " in value]\n if self.cfg.limit_examples_to_wandb > 0:\n eval_dict[key] = eval_dict[key][:self.cfg.limit_examples_to_wandb]\n columns, predictions = list(zip(*sorted...
gather_dict(eval_dict)
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "from optim.utils import get_batch\ndef get_args():\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--checkpoint', type=str, required=True)\n args, rem_args = parser.parse_known_args()\n if o...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
parser.add_argument('--dropout', default=0.0, type=float) parser.add_argument('--group_dropout', default=None, type=float, required=False) parser.add_argument('--n_head', default=8, type=int) parser.add_argument('--n_layer', default=12, type=int) # depths in att + ff blocks parser.add_argument('--n...
{ "context_start_lineno": 0, "file": "lm_benchmark/config/rotary.py", "groundtruth_start_lineno": 59, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 60, "task_id": "project_cc_python/8279" }
{ "list": [ { "filename": "lm_benchmark/main.py", "retrieved_chunk": " torch.cuda.set_device(args.device)\n device_type = 'cuda' if 'cuda' in str(args.device) else 'cpu'\n torch.manual_seed(args.seed)\n random.seed(args.seed)\n np.random.seed(args.seed)\n print(f\"Loading dataset '{a...
registered_models())
{ "list": [ { "filename": "trainer/tasks/base_task.py", "retrieved_chunk": " def evaluate(self, model, criterion, dataloader):\n pass\n def log_to_wandb(self, eval_dict, table_name=\"test_predictions\"):\n if not self.accelerator.is_main_process or not LoggerType.WANDB == self.acce...
import collections from dataclasses import dataclass import torch from PIL import Image from accelerate.logging import get_logger from accelerate.utils import LoggerType from omegaconf import II from transformers import AutoTokenizer from trainer.accelerators.base_accelerator import BaseAccelerator from trainer.tasks...
return metrics
{ "context_start_lineno": 0, "file": "trainer/tasks/clip_task.py", "groundtruth_start_lineno": 104, "repository": "yuvalkirstain-PickScore-5fa69e8", "right_context_start_lineno": 105, "task_id": "project_cc_python/8324" }
{ "list": [ { "filename": "trainer/tasks/base_task.py", "retrieved_chunk": " in value]\n if self.cfg.limit_examples_to_wandb > 0:\n eval_dict[key] = eval_dict[key][:self.cfg.limit_examples_to_wandb]\n columns, predictions = list(zip(*sorted...
log_to_wandb(eval_dict)
{ "list": [ { "filename": "pointstorm/embedding/text_tests.py", "retrieved_chunk": " metadata={\"author\": \"John Doe\"},\n text=[\"Hello, world!\"],\n embeddings=[[]]\n )\n self.assertEqual(doc.id, \"123\")\n self.assertEqual(doc.group_key, \"grou...
# Generic imports import json import logging import warnings import os import uuid warnings.filterwarnings(action = 'ignore') # Ingestion Imports from bytewax.testing import run_main from bytewax.dataflow import Dataflow from bytewax.connectors.kafka import KafkaInput from bytewax.connectors.stdio import StdOutput # f...
return doc def run(self): input_config = KafkaInput( brokers=[self.kafka_bootstrap_server], topics=[self.kafka_topic], add_config=self.kafka_config ) kafka_logger.info("Started KafkaTextEmbeddings for topic: " + self.kafka_topic) flo...
{ "context_start_lineno": 0, "file": "pointstorm/ingestion/event/kafka.py", "groundtruth_start_lineno": 63, "repository": "xsfa-pointstorm-ede28ec", "right_context_start_lineno": 64, "task_id": "project_cc_python/8407" }
{ "list": [ { "filename": "pointstorm/embedding/text_tests.py", "retrieved_chunk": "class TestGenerateEmbedding(unittest.TestCase):\n @patch.object(AutoTokenizer, 'from_pretrained')\n @patch.object(AutoModel, 'from_pretrained')\n def setUp(self, mock_model, mock_tokenizer):\n self.mock...
id}): {doc.embeddings}")
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": "from optim.utils import get_batch\ndef get_args():\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument('--checkpoint', type=str, required=True)\n args, rem_args = parser.parse_known_args()\n if o...
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
parser.add_argument('--mem_cache_size', default=None, type=int, required=False) parser.add_argument('--mem_cache_freq', default=None, type=int, required=False, help="Frequency to add landmark tokens in the input (block size at inference)") parser.add_argument('--cache_topk', default=1, type=int, required=F...
{ "context_start_lineno": 0, "file": "lm_benchmark/config/rotary.py", "groundtruth_start_lineno": 86, "repository": "epfml-landmark-attention-111ee30", "right_context_start_lineno": 87, "task_id": "project_cc_python/8282" }
{ "list": [ { "filename": "lm_benchmark/eval.py", "retrieved_chunk": " summary = json.load(f)\n for k, v in summary['args'].items():\n if k not in [\"device\", \"dtype\"]:\n setattr(args, k, v)\n return config.parse_args_with_format(format=args.config_format, base_parser...
caches.registered_caches())
{ "list": [ { "filename": "src/twyn/dependency_parser/requirements_txt.py", "retrieved_chunk": "\"\"\"Parser for requirements.txt dependencies.\"\"\"\nfrom dparse import filetypes, parse\nfrom dparse.dependencies import Dependency, DependencyFile\nfrom twyn.dependency_parser.abstract_parser import Abs...
from unittest.mock import patch import pytest from twyn.base.exceptions import TwynError from twyn.dependency_parser import PoetryLockParser, RequirementsTxtParser from twyn.dependency_parser.abstract_parser import AbstractParser from twyn.dependency_parser.exceptions import PathIsNotFileError, PathNotFoundError cla...
@patch("twyn.dependency_parser.abstract_parser.AbstractParser.raise_for_valid_file") def test_file_exists_fail(self, mock_raise_for_valid_file): def raise_twyn_error(): raise TwynError mock_raise_for_valid_file.side_effect = raise_twyn_error parser = self.TemporaryParser("...
{ "context_start_lineno": 0, "file": "tests/dependency_parser/test_dependency_parser.py", "groundtruth_start_lineno": 20, "repository": "elementsinteractive-twyn-4517d87", "right_context_start_lineno": 21, "task_id": "project_cc_python/8317" }
{ "list": [ { "filename": "src/twyn/dependency_parser/requirements_txt.py", "retrieved_chunk": " dependency_file: DependencyFile = parse(\n self._read(), file_type=filetypes.requirements_txt\n )\n dependencies: list[Dependency] = dependency_file.resolved_dependencies\n ...
file_exists() is True
{ "list": [ { "filename": "pointstorm/embedding/text_tests.py", "retrieved_chunk": " metadata={\"author\": \"John Doe\"},\n text=[\"Hello, world!\"],\n embeddings=[[]]\n )\n self.assertEqual(doc.id, \"123\")\n self.assertEqual(doc.group_key, \"grou...
# Generic imports import json import logging import warnings import os import uuid warnings.filterwarnings(action = 'ignore') # Ingestion Imports from bytewax.testing import run_main from bytewax.dataflow import Dataflow from bytewax.connectors.kafka import KafkaInput from bytewax.connectors.stdio import StdOutput # f...
return doc def run(self): input_config = KafkaInput( brokers=[self.kafka_bootstrap_server], topics=[self.kafka_topic], add_config=self.kafka_config ) kafka_logger.info("Started KafkaTextEmbeddings for topic: " + self.kafka_topic) flo...
{ "context_start_lineno": 0, "file": "pointstorm/ingestion/event/kafka.py", "groundtruth_start_lineno": 63, "repository": "xsfa-pointstorm-ede28ec", "right_context_start_lineno": 64, "task_id": "project_cc_python/8406" }
{ "list": [ { "filename": "pointstorm/embedding/text_tests.py", "retrieved_chunk": "class TestGenerateEmbedding(unittest.TestCase):\n @patch.object(AutoTokenizer, 'from_pretrained')\n @patch.object(AutoModel, 'from_pretrained')\n def setUp(self, mock_model, mock_tokenizer):\n self.mock...
info(f"Generated embeddings for message: {message} ({doc.id}): {doc.embeddings}")
{ "list": [ { "filename": "tests/dependency_parser/test_dependency_selector.py", "retrieved_chunk": " parser_obj,\n ):\n req_exists.return_value = requirements_exists\n poet_exists.return_value = poetry_exists\n parser = DependencySelector(file_name).get_dependency_parse...
from unittest.mock import patch import pytest from twyn.base.exceptions import TwynError from twyn.dependency_parser import PoetryLockParser, RequirementsTxtParser from twyn.dependency_parser.abstract_parser import AbstractParser from twyn.dependency_parser.exceptions import PathIsNotFileError, PathNotFoundError cla...
def test_parse_poetry_lock_file_ge_1_5(self, poetry_lock_file_ge_1_5): parser = PoetryLockParser(file_path=poetry_lock_file_ge_1_5) assert parser.parse() == {"charset-normalizer", "flake8", "mccabe"}
{ "context_start_lineno": 0, "file": "tests/dependency_parser/test_dependency_parser.py", "groundtruth_start_lineno": 56, "repository": "elementsinteractive-twyn-4517d87", "right_context_start_lineno": 57, "task_id": "project_cc_python/8320" }
{ "list": [ { "filename": "tests/dependency_parser/test_dependency_selector.py", "retrieved_chunk": " @patch(\"twyn.dependency_parser.abstract_parser.AbstractParser.file_exists\")\n def test_auto_detect_dependency_file_parser_exceptions(\n self, file_exists, exists, exception\n ):\n ...
parse() == {"charset-normalizer", "flake8", "mccabe"}
{ "list": [ { "filename": "tests/conftest.py", "retrieved_chunk": "import os\nimport pytest\[email protected]\ndef requirements_txt_file(tmp_path):\n requirements_txt_file = tmp_path / \"requirements.txt\"\n requirements_txt_file.write_text(\n \"\"\"\n South==1.0.1 --hash=sha256:abc...
from unittest.mock import patch import pytest from twyn.base.exceptions import TwynError from twyn.dependency_parser import PoetryLockParser, RequirementsTxtParser from twyn.dependency_parser.abstract_parser import AbstractParser from twyn.dependency_parser.exceptions import PathIsNotFileError, PathNotFoundError cla...
class TestPoetryLockParser: def test_parse_poetry_lock_file_lt_1_5(self, poetry_lock_file_lt_1_5): parser = PoetryLockParser(file_path=poetry_lock_file_lt_1_5) assert parser.parse() == {"charset-normalizer", "flake8", "mccabe"} def test_parse_poetry_lock_file_ge_1_5(self, poetry_lock_file_ge...
{ "context_start_lineno": 0, "file": "tests/dependency_parser/test_dependency_parser.py", "groundtruth_start_lineno": 50, "repository": "elementsinteractive-twyn-4517d87", "right_context_start_lineno": 51, "task_id": "project_cc_python/8319" }
{ "list": [ { "filename": "tests/dependency_parser/test_dependency_selector.py", "retrieved_chunk": " DependencySelector(file_name).get_dependency_file_parser_from_file_name()", "score": 35.08187387907704 }, { "filename": "tests/dependency_parser/test_dependency_selector...
parse() == {"South", "pycrypto"}
{ "list": [ { "filename": "pointstorm/producers/text_producer.py", "retrieved_chunk": " \"\"\"\n def __init__(self, kafka_topic, config):\n self.topic = kafka_topic\n self.config = config\n self.producer = Producer(config)\n def produce(self, text):\n def receipt(e...
from pointstorm.producers.text_producer import TextProducer from faker import Faker fake = Faker() # Create Kafka Producer kafka_config = { 'bootstrap.servers':'localhost:9092', } kafka_topic = "user-tracker2" p = TextProducer(kafka_topic, kafka_config) print('Kafka Producer has been initiated...') # Producing ...
produce()
{ "context_start_lineno": 0, "file": "pointstorm/examples/kafka/kafka_producer.py", "groundtruth_start_lineno": 19, "repository": "xsfa-pointstorm-ede28ec", "right_context_start_lineno": 20, "task_id": "project_cc_python/8409" }
{ "list": [ { "filename": "pointstorm/producers/text_producer.py", "retrieved_chunk": " \"\"\"\n def __init__(self, kafka_topic, config):\n self.topic = kafka_topic\n self.config = config\n self.producer = Producer(config)\n def produce(self, text):\n def receipt(e...
produce(sentence)
{ "list": [ { "filename": "pointstorm/ingestion/event/kafka.py", "retrieved_chunk": " doc = Document(\n id=str(uuid.uuid4()),\n group_key=\"group1\",\n metadata={},\n text=[message],\n embeddings=[[]]\n )\n doc = generate_embe...
import unittest from pointstorm.embedding.text import Document, generate_embedding from unittest.mock import patch, MagicMock from transformers import AutoTokenizer, AutoModel import torch class TestDocumentModel(unittest.TestCase): def test_document_model_creation(self): doc = Document( id="12...
@patch("builtins.print") class TestGenerateEmbedding(unittest.TestCase): @patch.object(AutoTokenizer, 'from_pretrained') @patch.object(AutoModel, 'from_pretrained') def setUp(self, mock_model, mock_tokenizer): self.mock_model = mock_model self.mock_tokenizer = mock_tokenizer self....
{ "context_start_lineno": 0, "file": "pointstorm/embedding/text_tests.py", "groundtruth_start_lineno": 19, "repository": "xsfa-pointstorm-ede28ec", "right_context_start_lineno": 20, "task_id": "project_cc_python/8414" }
{ "list": [ { "filename": "pointstorm/ingestion/event/kafka.py", "retrieved_chunk": " model=self.model\n )\n kafka_logger.info(f\"Generated embeddings for message: {message} ({doc.id}): {doc.embeddings}\")\n return doc\n def run(self):\n input_config = KafkaIn...
embeddings, [[]])
{ "list": [ { "filename": "src/mokka/inft/torch.py", "retrieved_chunk": " -------\n BMI : float\n bitwise mutual information\n \"\"\"\n if p is not None:\n entropy = torch.sum(-p * torch.log2(p))\n else:\n entropy = m\n BMI = entropy - 1 / N * torch.sum(\...
"""Normalization for communication systems in PyTorch.""" import torch def energy(c, p=None): """ Perform normalization on average energy. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: constellation with average energy 1 """...
else: scaling = torch.sqrt((c.size()[-1]) / torch.sum(torch.abs(c) ** 2, -1)) scaling = torch.unsqueeze(scaling, -1).repeat(*((1,) * len(c.size())), c.size()[-1]) scaling = torch.squeeze(scaling, 0) c = torch.multiply(c, scaling) return c def centered_energy(c, p=None): """Perform cen...
{ "context_start_lineno": 0, "file": "src/mokka/normalization/torch.py", "groundtruth_start_lineno": 14, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 15, "task_id": "project_cc_python/8334" }
{ "list": [ { "filename": "src/mokka/inft/torch.py", "retrieved_chunk": " 1\n + torch.exp(\n torch.clip(\n -1 * torch.pow(-1, b_ij) * L_ij,\n max=torch.tensor(88.0).to(b_ij.device),\n )\n )\n )\...
sqrt(1.0 / torch.sum(p * (torch.abs(c) ** 2), -1))
{ "list": [ { "filename": "src/mokka/utils/__init__.py", "retrieved_chunk": " :param y: power in linear units [W]\n :returns: power in decibel [dBW]\n \"\"\"\n return 10 * torch.log10(y)\ndef pow2dbm(y):\n \"\"\"Calculate the power in dBm.\n :param y: power in linear units [W]\n :...
"""Data generators implemented in NumPy.""" import numpy as np import os import sys seed = int.from_bytes(os.urandom(4), byteorder=sys.byteorder) gen = np.random.default_rng(seed) def generate_BPSK(N, P_in_dbm): """Generate BPSK symbols with a given power. :param N: Number of BPSK symbols to generate :p...
samples = gen.choice(symbols, (N,)) return samples def generate_bits(shape): """Generate uniform random bits. :param shape: tuple with resulting shape :returns: array with uniform random bits in the requested shape """ bits = np.random.choice([0, 1], shape) return bits def generat...
{ "context_start_lineno": 0, "file": "src/mokka/utils/generators/numpy.py", "groundtruth_start_lineno": 18, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 19, "task_id": "project_cc_python/8328" }
{ "list": [ { "filename": "src/mokka/utils/__init__.py", "retrieved_chunk": "def db2pow(ydb):\n \"\"\"Calculate the power in linear units.\n :param ydb: power in decibel [dB]\n :returns: power in linear units [W]\n \"\"\"\n return 10 ** (ydb / 10)\ndef dbm2pow(ydbm):\n \"\"\"Calculat...
sqrt(P_in)
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " else:\n c = normalization.energy(c, self.p_symbols)\n logger.debug(\"c device: %s\", c.device)\n logger.debug(\"c size after scaling: %s\", c.size())\n logger.debug(\"c energy for item 0...
"""Normalization for communication systems in PyTorch.""" import torch def energy(c, p=None): """ Perform normalization on average energy. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: constellation with average energy 1 """...
c = torch.multiply(c, scaling) return c def centered_energy(c, p=None): """Perform centered (zero-mean) normalization of the complex constellation. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: centered constellation with av...
{ "context_start_lineno": 0, "file": "src/mokka/normalization/torch.py", "groundtruth_start_lineno": 18, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 19, "task_id": "project_cc_python/8338" }
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " def get_constellation(self, *args):\n \"\"\"\n Return constellation for all input bits.\n :params args: same arguments as for forward() if constellation mapper is\n parametrized\n ...
squeeze(scaling, 0)
{ "list": [ { "filename": "src/mokka/utils/__init__.py", "retrieved_chunk": " :param y: power in linear units [W]\n :returns: power in decibel [dBW]\n \"\"\"\n return 10 * torch.log10(y)\ndef pow2dbm(y):\n \"\"\"Calculate the power in dBm.\n :param y: power in linear units [W]\n :...
"""Data generators implemented in NumPy.""" import numpy as np import os import sys seed = int.from_bytes(os.urandom(4), byteorder=sys.byteorder) gen = np.random.default_rng(seed) def generate_BPSK(N, P_in_dbm): """Generate BPSK symbols with a given power. :param N: Number of BPSK symbols to generate :p...
samples = gen.choice(symbols, (N,)) return samples def generate_bits(shape): """Generate uniform random bits. :param shape: tuple with resulting shape :returns: array with uniform random bits in the requested shape """ bits = np.random.choice([0, 1], shape) return bits def generat...
{ "context_start_lineno": 0, "file": "src/mokka/utils/generators/numpy.py", "groundtruth_start_lineno": 18, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 19, "task_id": "project_cc_python/8327" }
{ "list": [ { "filename": "src/mokka/utils/__init__.py", "retrieved_chunk": "def db2pow(ydb):\n \"\"\"Calculate the power in linear units.\n :param ydb: power in decibel [dB]\n :returns: power in linear units [W]\n \"\"\"\n return 10 ** (ydb / 10)\ndef dbm2pow(ydbm):\n \"\"\"Calculat...
array([-1, 1]) * np.sqrt(P_in)
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " else:\n c = normalization.energy(c, self.p_symbols)\n logger.debug(\"c device: %s\", c.device)\n logger.debug(\"c size after scaling: %s\", c.size())\n logger.debug(\"c energy for item 0...
"""Normalization for communication systems in PyTorch.""" import torch def energy(c, p=None): """ Perform normalization on average energy. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: constellation with average energy 1 """...
return c def centered_energy(c, p=None): """Perform centered (zero-mean) normalization of the complex constellation. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: centered constellation with average energy of 1 """ if p...
{ "context_start_lineno": 0, "file": "src/mokka/normalization/torch.py", "groundtruth_start_lineno": 19, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 20, "task_id": "project_cc_python/8339" }
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " def get_constellation(self, *args):\n \"\"\"\n Return constellation for all input bits.\n :params args: same arguments as for forward() if constellation mapper is\n parametrized\n ...
multiply(c, scaling)
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " \"noise_mean\",\n torch.nn.Parameter(noise_mean),\n )\n all_bits = np.arange(2**m, dtype=np.uint8)\n all_bits = np.expand_dims(all_bits, 1)\n B = np.unpackbits(all_bits, axis=...
"""Data generators implemented in NumPy.""" import numpy as np import os import sys seed = int.from_bytes(os.urandom(4), byteorder=sys.byteorder) gen = np.random.default_rng(seed) def generate_BPSK(N, P_in_dbm): """Generate BPSK symbols with a given power. :param N: Number of BPSK symbols to generate :p...
return B
{ "context_start_lineno": 0, "file": "src/mokka/utils/generators/numpy.py", "groundtruth_start_lineno": 44, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 45, "task_id": "project_cc_python/8332" }
{ "list": [ { "filename": "src/mokka/utils/bitops/numpy.py", "retrieved_chunk": " \"\"\"\n nums = np.arange(2**m, dtype=np.uint8)\n bits = idx2bits(nums, m)\n return bits\ndef gray(m):\n \"\"\"Generate a sequence of bit strings with binary-reflected Gray coding.\n :param m: length of...
flip(np.unpackbits(all_bits, axis=1, count=m, bitorder="little"), axis=1)
{ "list": [ { "filename": "api/routers/bridge.py", "retrieved_chunk": " # if the pid file is empty and the process is not None and is alive,\n # then return that the bridge is starting\n if pid == 0 and process_state == ProcessStateEnum.RUNNING:\n return BridgeResponseS...
"""handles the process of the bridge between telegram and discord""" import argparse import asyncio import os import signal import sys from asyncio import AbstractEventLoop from sqlite3 import OperationalError from typing import Tuple import discord import psutil # pylint: disable=import-error from telethon import T...
except PermissionError: # If the PID file exists and the PID of the process that created it is # running, the process is considered running. return ProcessStateEnum.RUNNING, pid except FileNotFoundError: # The PID file does not exist, so the process is considered stopped. ...
{ "context_start_lineno": 0, "file": "forwarder.py", "groundtruth_start_lineno": 149, "repository": "hyp3rd-telegram-discord-bridge-24fa2fb", "right_context_start_lineno": 150, "task_id": "project_cc_python/8367" }
{ "list": [ { "filename": "api/routers/bridge.py", "retrieved_chunk": " ))\n # otherwise return the state of the process\n return BridgeResponseSchema(bridge=BridgeResponse(\n name=config.app.name,\n status=ProcessStateEnum.RUNNING,\n process_i...
ORPHANED, 0
{ "list": [ { "filename": "api/routers/config.py", "retrieved_chunk": " enabled=self.config.api.enabled,\n cors_origins=self.config.api.cors_origins,\n telegram_login_enabled=self.config.api.telegram_login_enabled,\n telegram_auth_file=self.config.api.telegr...
"""Create a logger for the application.""""" import logging from logging.handlers import RotatingFileHandler from logging import StreamHandler from bridge.config import LoggerConfig import bridge.logger.formatter as log_formatter class Logger(logging.Logger): """Singleton logger class. It allows to create only on...
if not logger_config.console: # The log files will rotate when they reach 10 MB in size. # The backupCount parameter is set to 5, # which means that up to 5 backup files will be kept. handler = RotatingFileHandler( f'{file_name}.log', ...
{ "context_start_lineno": 0, "file": "bridge/logger/logger.py", "groundtruth_start_lineno": 47, "repository": "hyp3rd-telegram-discord-bridge-24fa2fb", "right_context_start_lineno": 48, "task_id": "project_cc_python/8380" }
{ "list": [ { "filename": "api/routers/config.py", "retrieved_chunk": " format=self.config.logger.format,\n date_format=self.config.logger.date_format,\n console=self.config.logger.console,\n )\n telegram_config = TelegramConfig(\n phone=self.c...
ColourizedFormatter(use_colors=logger_config.console, fmt=logger_config.format)
{ "list": [ { "filename": "src/mokka/inft/torch.py", "retrieved_chunk": " -------\n BMI : float\n bitwise mutual information\n \"\"\"\n if p is not None:\n entropy = torch.sum(-p * torch.log2(p))\n else:\n entropy = m\n BMI = entropy - 1 / N * torch.sum(\...
"""Normalization for communication systems in PyTorch.""" import torch def energy(c, p=None): """ Perform normalization on average energy. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: constellation with average energy 1 """...
else: scaling = torch.sqrt((c.size()[-1]) / torch.sum(torch.abs(c) ** 2, -1)) scaling = torch.unsqueeze(scaling, -1).repeat(*((1,) * len(c.size())), c.size()[-1]) scaling = torch.squeeze(scaling, 0) c = torch.multiply(c, scaling) return c def centered_energy(c, p=None): """Perform cen...
{ "context_start_lineno": 0, "file": "src/mokka/normalization/torch.py", "groundtruth_start_lineno": 14, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 15, "task_id": "project_cc_python/8335" }
{ "list": [ { "filename": "src/mokka/inft/torch.py", "retrieved_chunk": " 1\n + torch.exp(\n torch.clip(\n -1 * torch.pow(-1, b_ij) * L_ij,\n max=torch.tensor(88.0).to(b_ij.device),\n )\n )\n )\...
sum(p * (torch.abs(c) ** 2), -1))
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " def __init__(self, m, qam_init=False):\n \"\"\"Construct SimpleConstellationMapper.\"\"\"\n super(SimpleConstellationMapper, self).__init__()\n self.register_buffer(\"m\", torch.tensor(m))\n if ...
from mokka import mapping import numpy as np # PyTorch tests def test_simple_constellation_mapper_random(): m = 4 mapper = mapping.torch.SimpleConstellationMapper(m) symbols = mapper.get_constellation() assert symbols.shape[0] == 16 def test_simple_constellation_mapper_qaminit(): m = 4 mapp...
assert np.allclose(symbols, reference_symbols) def test_regular_constellation_mapper_random(): m = 4 mapper = mapping.torch.ConstellationMapper(m) symbols = mapper.get_constellation() assert symbols.shape[0] == 16 def test_regular_constellation_mapper_qaminit(): m = 4 mapper = mapping.t...
{ "context_start_lineno": 0, "file": "tests/mokka/test_mapping.py", "groundtruth_start_lineno": 17, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 18, "task_id": "project_cc_python/8341" }
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " np.stack((symbols.real, symbols.imag), axis=-1),\n dtype=torch.float32,\n ),\n ),\n )\n else:\n self.weights = torch...
numpy.QAM(m).get_constellation().flatten()
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " torch.nn.Parameter(torch.tensor(noise_sigma, dtype=torch.float32)),\n )\n else:\n self.noise_sigma = noise_sigma\n self.constellation = constellation\n M = torch.numel...
from mokka.utils import generators from mokka.utils import bitops import torch import numpy as np def test_generatebits(): bits = generators.numpy.generate_bits((1, 10)) assert bits.shape == (1, 10) def test_generate_all_bits(): m = 4 all_bits = generators.numpy.generate_all_bits(m) assert all_b...
{ "context_start_lineno": 0, "file": "tests/mokka/test_utils.py", "groundtruth_start_lineno": 24, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 25, "task_id": "project_cc_python/8347" }
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " B = np.unpackbits(all_bits, axis=1, count=m, bitorder=\"little\")\n self.bits = torch.from_numpy(B).to(constellation.device)\n with torch.no_grad():\n self.one_idx = torch.nonzero(self.bits)\n ...
all(one_hot == expected_result)
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " torch.nn.Parameter(torch.tensor(noise_sigma, dtype=torch.float32)),\n )\n else:\n self.noise_sigma = noise_sigma\n self.constellation = constellation\n M = torch.numel...
from mokka.utils import generators from mokka.utils import bitops import torch import numpy as np def test_generatebits(): bits = generators.numpy.generate_bits((1, 10)) assert bits.shape == (1, 10) def test_generate_all_bits(): m = 4 all_bits = generators.numpy.generate_all_bits(m) assert all_b...
for idx in range(2**m): expected_result[idx][idx] = 1.0 assert torch.all(one_hot == expected_result)
{ "context_start_lineno": 0, "file": "tests/mokka/test_utils.py", "groundtruth_start_lineno": 21, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 22, "task_id": "project_cc_python/8346" }
{ "list": [ { "filename": "src/mokka/utils/generators/numpy.py", "retrieved_chunk": " # Generate bits from 0 to 2**m\n B = np.flip(np.unpackbits(all_bits, axis=1, count=m, bitorder=\"little\"), axis=1)\n return B", "score": 58.65918579295341 }, { "filename": "src/mokka/map...
zeros((2**m, 2**m)))
{ "list": [ { "filename": "src/mokka/utils/generators/numpy.py", "retrieved_chunk": " \"\"\"\n bits = np.random.choice([0, 1], shape)\n return bits\ndef generate_all_bits(m):\n \"\"\"Generate all possible bitstrings of length m.\n :param m: length of the bitstring\n :returns: array w...
from mokka.utils import generators from mokka.utils import bitops import torch import numpy as np def test_generatebits(): bits = generators.numpy.generate_bits((1, 10)) assert bits.shape == (1, 10) def test_generate_all_bits(): m = 4 all_bits = generators.numpy.generate_all_bits(m) assert all_b...
expected_result = torch.tensor(np.zeros((2**m, 2**m))) for idx in range(2**m): expected_result[idx][idx] = 1.0 assert torch.all(one_hot == expected_result)
{ "context_start_lineno": 0, "file": "tests/mokka/test_utils.py", "groundtruth_start_lineno": 20, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 21, "task_id": "project_cc_python/8344" }
{ "list": [ { "filename": "src/mokka/utils/generators/numpy.py", "retrieved_chunk": " # Generate bits from 0 to 2**m\n B = np.flip(np.unpackbits(all_bits, axis=1, count=m, bitorder=\"little\"), axis=1)\n return B", "score": 52.97914350866145 }, { "filename": "tests/mokka/t...
torch.bits_to_onehot(torch.tensor(all_bits.copy()))
{ "list": [ { "filename": "src/mokka/utils/generators/numpy.py", "retrieved_chunk": " \"\"\"\n bits = np.random.choice([0, 1], shape)\n return bits\ndef generate_all_bits(m):\n \"\"\"Generate all possible bitstrings of length m.\n :param m: length of the bitstring\n :returns: array w...
from mokka.utils import generators from mokka.utils import bitops import torch import numpy as np def test_generatebits(): bits = generators.numpy.generate_bits((1, 10)) assert bits.shape == (1, 10) def test_generate_all_bits(): m = 4 all_bits = generators.numpy.generate_all_bits(m) assert all_b...
expected_result = torch.tensor(np.zeros((2**m, 2**m))) for idx in range(2**m): expected_result[idx][idx] = 1.0 assert torch.all(one_hot == expected_result)
{ "context_start_lineno": 0, "file": "tests/mokka/test_utils.py", "groundtruth_start_lineno": 20, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 21, "task_id": "project_cc_python/8345" }
{ "list": [ { "filename": "src/mokka/utils/generators/numpy.py", "retrieved_chunk": " # Generate bits from 0 to 2**m\n B = np.flip(np.unpackbits(all_bits, axis=1, count=m, bitorder=\"little\"), axis=1)\n return B", "score": 52.97914350866145 }, { "filename": "tests/mokka/t...
tensor(all_bits.copy()))
{ "list": [ { "filename": "src/mokka/mapping/torch.py", "retrieved_chunk": " \"noise_mean\",\n torch.nn.Parameter(noise_mean),\n )\n all_bits = np.arange(2**m, dtype=np.uint8)\n all_bits = np.expand_dims(all_bits, 1)\n B = np.unpackbits(all_bits, axis=...
"""Data generators implemented in NumPy.""" import numpy as np import os import sys seed = int.from_bytes(os.urandom(4), byteorder=sys.byteorder) gen = np.random.default_rng(seed) def generate_BPSK(N, P_in_dbm): """Generate BPSK symbols with a given power. :param N: Number of BPSK symbols to generate :p...
return B
{ "context_start_lineno": 0, "file": "src/mokka/utils/generators/numpy.py", "groundtruth_start_lineno": 44, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 45, "task_id": "project_cc_python/8333" }
{ "list": [ { "filename": "src/mokka/utils/bitops/numpy.py", "retrieved_chunk": " \"\"\"\n nums = np.arange(2**m, dtype=np.uint8)\n bits = idx2bits(nums, m)\n return bits\ndef gray(m):\n \"\"\"Generate a sequence of bit strings with binary-reflected Gray coding.\n :param m: length of...
unpackbits(all_bits, axis=1, count=m, bitorder="little"), axis=1)
{ "list": [ { "filename": "server/events/broadcaster_test.py", "retrieved_chunk": "def test_parse_worker_event_missing_hostname(caplog: pytest.LogCaptureFixture):\n event = {\"type\": \"worker-started\"}\n assert parse_worker_event(event, \"worker-started\") is None\n assert \"Worker event 'w...
import pytest from pytest_mock import MockerFixture from ws.websocket_manager import WebsocketManager class FakeWebSocket: def __init__(self, name: str): self.client = name # noinspection PyMethodMayBeStatic async def send_text(self) -> str: return "" def test_websocket_manager_subscr...
def test_websocket_manager_unsubscribe(caplog: pytest.LogCaptureFixture): manager = WebsocketManager("test") ws = FakeWebSocket("Fake Client") manager.active_connections.append(ws) # type: ignore with caplog.at_level("INFO"): manager.unsubscribe(ws) # type: ignore assert ws not in man...
{ "context_start_lineno": 0, "file": "server/ws/websocket_manager_test.py", "groundtruth_start_lineno": 25, "repository": "danyi1212-celery-insights-a742653", "right_context_start_lineno": 26, "task_id": "project_cc_python/8359" }
{ "list": [ { "filename": "server/ws/websocket_manager.py", "retrieved_chunk": " for connection in self.active_connections\n ], return_exceptions=True\n )\n for result, connection in zip(results, self.active_connections, strict=True):\n if isinsta...
name) in caplog.messages[-1]
{ "list": [ { "filename": "src/mokka/inft/torch.py", "retrieved_chunk": " -------\n BMI : float\n bitwise mutual information\n \"\"\"\n if p is not None:\n entropy = torch.sum(-p * torch.log2(p))\n else:\n entropy = m\n BMI = entropy - 1 / N * torch.sum(\...
"""Normalization for communication systems in PyTorch.""" import torch def energy(c, p=None): """ Perform normalization on average energy. :param c: complex constellation points :param p: probabilities, if None: uniform probability is assumed :returns: constellation with average energy 1 """...
else: scaling = torch.sqrt((c.size()[-1]) / torch.sum(torch.abs(c) ** 2, -1)) scaling = torch.unsqueeze(scaling, -1).repeat(*((1,) * len(c.size())), c.size()[-1]) scaling = torch.squeeze(scaling, 0) c = torch.multiply(c, scaling) return c def centered_energy(c, p=None): """Perform cen...
{ "context_start_lineno": 0, "file": "src/mokka/normalization/torch.py", "groundtruth_start_lineno": 14, "repository": "kit-cel-mokka-8a555d9", "right_context_start_lineno": 15, "task_id": "project_cc_python/8336" }
{ "list": [ { "filename": "src/mokka/inft/torch.py", "retrieved_chunk": " 1\n + torch.exp(\n torch.clip(\n -1 * torch.pow(-1, b_ij) * L_ij,\n max=torch.tensor(88.0).to(b_ij.device),\n )\n )\n )\...
abs(c) ** 2), -1))
{ "list": [ { "filename": "server/api_server.py", "retrieved_chunk": " if bot is None:\n logger.error(f\"chat ask,ip:{request.client.host},bot none\")\n return {\"code\":sc.ERROR.code,\"msg\":sc.ERROR.msg}\n st = bot.input(prompt, history = session.get_history())\n if type(st) i...
import asyncio import time import sys import threading from utils.utils import get_rand_hex from utils.kv import KV import concurrent.futures import threading thpool = concurrent.futures.ThreadPoolExecutor(max_workers = 10) class Bot: def __init__(self, **kwargs): self.status = "open" self.kv = K...
return stub def stub_out(self, stub): if not self.kv.has(stub): return None return self.kv.get(stub) def stub_del(self, stub): if self.kv.has(stub): self.kv.remove(stub) def input(self, prompt, **kwargs): stub = self.stub_in(None) i...
{ "context_start_lineno": 0, "file": "backend/bot.py", "groundtruth_start_lineno": 29, "repository": "llmapi-io-llmapi-server-cdae9ca", "right_context_start_lineno": 30, "task_id": "project_cc_python/8455" }
{ "list": [ { "filename": "server/api_server.py", "retrieved_chunk": " reply = bot.output(stub=st)\n if reply is None:\n logger.warn(f\"chat ask,ip:{request.client.host},reply timeout\")\n return {\"code\":sc.REPLY_TIMEOUT.code,\"msg\":sc.REPLY_TIMEOUT.msg}\n session.add_con...
set(stub, val)
{ "list": [ { "filename": "backend/mock/mock.py", "retrieved_chunk": "from backend.bot import Bot\nimport time\nclass BotMock(Bot):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.status = \"open\"\n def open(self, **kwargs):\n if self.status != \"close\"...
import asyncio import time import sys import threading from utils.utils import get_rand_hex from utils.kv import KV import concurrent.futures import threading thpool = concurrent.futures.ThreadPoolExecutor(max_workers = 10) class Bot: def __init__(self, **kwargs): self.status = "open" self.kv = K...
return None stub = st if st is None: stub = get_rand_hex() self.kv.set(stub, val) return stub def stub_out(self, stub): if not self.kv.has(stub): return None return self.kv.get(stub) def stub_del(self, stub): if self...
{ "context_start_lineno": 0, "file": "backend/bot.py", "groundtruth_start_lineno": 23, "repository": "llmapi-io-llmapi-server-cdae9ca", "right_context_start_lineno": 24, "task_id": "project_cc_python/8454" }
{ "list": [ { "filename": "backend/mock/mock.py", "retrieved_chunk": " def task_impl(self, prompt:str, history:dict = None, **kwargs) -> str:\n time.sleep(1)\n return \"Mock reply for your prompt:\" + prompt\n def reset(self, **kwargs):\n pass\n def close(self, **kwargs):...
size() > 10:
{ "list": [ { "filename": "src/optarber/deribit_ws.py", "retrieved_chunk": " \"grant_type\" : \"client_credentials\",\n \"client_id\" : self.client_id,\n \"client_secret\" : self.client_secret\n }\n self.json[\"method\"] = \"public/auth\"\n self.js...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.client_ws.change_summary(curr) def connect(self): self.disconnect() key = self.window.comboEnv.currentText() curr = self.window.comboCurr.currentText() api_key = self.cfg[key]["api_key"] api_secret = self.cfg[key]["api_secret"] ws_url = self.cfg[key]["ws_url"] self.client_rest = RestClient(ap...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 80, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 81, "task_id": "project_cc_python/8500" }
{ "list": [ { "filename": "src/optarber/mainUI.py", "retrieved_chunk": " optionAtillaWindow.setWindowTitle(_translate(\"optionAtillaWindow\", \"OptionAtilla\"))\n self.groupCriteria.setTitle(_translate(\"optionAtillaWindow\", \"Criteria\"))\n self.labelStrikePercent.setText(_trans...
account_summary(curr)
{ "list": [ { "filename": "src/optarber/results_model.py", "retrieved_chunk": "from PyQt6 import QtCore, QtGui\nclass ResultsModel(QtCore.QAbstractTableModel): \n def __init__(self, parent=None, *args): \n super(ResultsModel, self).__init__()\n self.results = None\n def update(self...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.position_model.update(self.positions) self.selection_model.update(self.selections) self.results_model.update(self.results) self.cfg = configparser.ConfigParser() self.cfg.read(config_file) self.client_ws = None self.client_rest = None self.window = None self.mainW = None def setWindow(self...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 38, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 39, "task_id": "project_cc_python/8495" }
{ "list": [ { "filename": "src/optarber/results_model.py", "retrieved_chunk": " return self.results.getCols()\n def data(self, index, role=QtCore.Qt):\n if self.results is not None:\n i = index.row()\n j = index.column()\n if role == QtCore.Qt.ItemData...
update(self.account)
{ "list": [ { "filename": "utils/kv.py", "retrieved_chunk": " return ks\n def size(self):\n return len(self.kvs)\n def remove(self,key):\n if self.has(key):\n del self.kvs[key]\ndef _test():\n kv = KV()\n for i in range(1000):\n kv.set(i,i*i)", ...
import asyncio import time import sys import threading from utils.utils import get_rand_hex from utils.kv import KV import concurrent.futures import threading thpool = concurrent.futures.ThreadPoolExecutor(max_workers = 10) class Bot: def __init__(self, **kwargs): self.status = "open" self.kv = K...
def input(self, prompt, **kwargs): stub = self.stub_in(None) if stub is None: return None self._run(stub=stub,prompt=prompt, **kwargs) return stub def output(self, stub, **kwargs): res = self.stub_out(stub) if res is not None: self.stub_...
{ "context_start_lineno": 0, "file": "backend/bot.py", "groundtruth_start_lineno": 39, "repository": "llmapi-io-llmapi-server-cdae9ca", "right_context_start_lineno": 40, "task_id": "project_cc_python/8458" }
{ "list": [ { "filename": "utils/kv.py", "retrieved_chunk": " sz = kv.size()\n assert(sz == 1000)\n v = kv.get(100)\n assert(v == 10000)\n for i in range(100):\n kv.remove(i)\n sz = kv.size()\n assert(sz == 900)\n v = kv.get(10)\n assert(v == None)", "score": 46...
remove(stub)
{ "list": [ { "filename": "server/session.py", "retrieved_chunk": " elif bot_type == 'gpt-embedding':\n key = GPT_EMBEDDING_KEYS[random.randint(0, len(GPT_EMBEDDING_KEYS) - 1)]\n self.bot = LLMBackend(bot_type, api_key = key, model = self.model)\n elif bot_type == '...
import asyncio from backend.chatgpt.chatgpt import BotChatGPT from backend.gpt3.gpt3 import BotGPT3 from backend.mock.mock import BotMock from backend.welm.welm import BotWelm from backend.newbing.newbing import BotNewBing from backend.chatgpt.embedding import BotGPTEmbedding from backend.dalle.dalle import BotDALLE ...
def output(self, **kwargs): return self.bot.output(**kwargs) def reset(self, **kwargs): self.bot.reset(**kwargs) def close(self, **kwargs): self.bot.close(**kwargs)
{ "context_start_lineno": 0, "file": "backend/backend.py", "groundtruth_start_lineno": 32, "repository": "llmapi-io-llmapi-server-cdae9ca", "right_context_start_lineno": 33, "task_id": "project_cc_python/8466" }
{ "list": [ { "filename": "server/session.py", "retrieved_chunk": " self.session_id = get_short_hash(info)\n self.conversations = self.Conversations()\n self.last_use = time.time()\n def get_id(self):\n self.last_use = time.time()\n return self.session_id\n def...
input(prompt=prompt, **kwargs)
{ "list": [ { "filename": "src/optarber/deribit_rest.py", "retrieved_chunk": " def getportfoliomargin(self, curr, instrs):\n options = {\n 'currency':curr, \n 'simulated_positions': json.dumps(instrs),\n 'add_positions': 'true'\n }\n response...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
def connect(self): self.disconnect() key = self.window.comboEnv.currentText() curr = self.window.comboCurr.currentText() api_key = self.cfg[key]["api_key"] api_secret = self.cfg[key]["api_secret"] ws_url = self.cfg[key]["ws_url"] self.client_rest = RestClient(api_key, api_secret, False if key == "PR...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 81, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 82, "task_id": "project_cc_python/8501" }
{ "list": [ { "filename": "src/optarber/deribit_ws.py", "retrieved_chunk": " response = json.loads(textMessage)\n if \"id\" in response and response[\"id\"] == 2:\n if \"result\" in response:\n if \"token_type\" in response['result']:\n print(...
change_summary(curr)
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent_helper/use_tool.py", "retrieved_chunk": " # Remove those parameters that are not part of Python's `requests` function.\n tool_args.pop(\"jsonParams\", None)\n tool_args.pop(\"urlParams\", None)\n # print_big(tool_args, \"ARGS\")\n ...
import requests import traceback import os import random import concurrent.futures import openai import urllib.request import json import string import re import sys def flatten(a): return sum(a, []) def print_op(*kargs, **kwargs): print(*kargs, **kwargs, flush=True) def prepPrintPromptContext(p): re...
# print_op("FINAL URL: (" + tool["method"] + ") ", resp.url) actual_call = str(tool_args) if resp.status_code in [404, 401, 500]: er = " => " + str(resp.status_code) return "This tool isn't working currently" + er ret = str(resp.text) if self.verbose > 4: print(ret) ...
{ "context_start_lineno": 0, "file": "src/llm_vm/agents/REBEL/utils.py", "groundtruth_start_lineno": 208, "repository": "anarchy-ai-LLM-VM-83da960", "right_context_start_lineno": 209, "task_id": "project_cc_python/8402" }
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent_helper/use_tool.py", "retrieved_chunk": " elif method == \"PATCH\":\n request_function = requests.patch\n elif method == \"DELETE\":\n request_function = requests.delete\n elif method == \"GET\":\n request_function =...
post)(**tool_args)
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent_helper/use_tool.py", "retrieved_chunk": " # Remove those parameters that are not part of Python's `requests` function.\n tool_args.pop(\"jsonParams\", None)\n tool_args.pop(\"urlParams\", None)\n # print_big(tool_args, \"ARGS\")\n ...
import requests import traceback import os import random import concurrent.futures import openai import urllib.request import json import string import re import sys def flatten(a): return sum(a, []) def print_op(*kargs, **kwargs): print(*kargs, **kwargs, flush=True) def prepPrintPromptContext(p): re...
# print_op("FINAL URL: (" + tool["method"] + ") ", resp.url) actual_call = str(tool_args) if resp.status_code in [404, 401, 500]: er = " => " + str(resp.status_code) return "This tool isn't working currently" + er ret = str(resp.text) if self.verbose > 4: print(ret) ...
{ "context_start_lineno": 0, "file": "src/llm_vm/agents/REBEL/utils.py", "groundtruth_start_lineno": 208, "repository": "anarchy-ai-LLM-VM-83da960", "right_context_start_lineno": 209, "task_id": "project_cc_python/8401" }
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent_helper/use_tool.py", "retrieved_chunk": " elif method == \"PATCH\":\n request_function = requests.patch\n elif method == \"DELETE\":\n request_function = requests.delete\n elif method == \"GET\":\n request_function =...
get if tool["method"] == "GET" else requests.post)(**tool_args)
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent.py", "retrieved_chunk": " # tools = [{'method': 'GET',\"description\":\"use this tool to find the price of stocks\",'args' : {\"url\":\"https://finnhub.io/api/v1/quote\",'params': { 'token' :'cfi1v29r01qq9nt1nu4gcfi1v29r01qq9nt1nu50'} },\"dyna...
""" This file has been temporarily repurposed as an interface for users to call any of the three agents (REBEL, BACKWARD_CHAINING, and FLAT) and interact with them. Running this file prompts the user to choose any of the agents and ask it questions. """ import llm_vm.agents.REBEL.agent as REBEL import llm_vm.agents.FLA...
pass mem = [] last = "" while True: inp = input(last+"Human: ") ret = agent.run(inp, mem) mem = ret[1] last = "AI: "+str(ret[0])+ "\n" if __name__ == "__main__": call_agent()
{ "context_start_lineno": 0, "file": "src/llm_vm/agents/agent_interface.py", "groundtruth_start_lineno": 49, "repository": "anarchy-ai-LLM-VM-83da960", "right_context_start_lineno": 50, "task_id": "project_cc_python/8400" }
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent.py", "retrieved_chunk": " label = Agent(os.getenv(\"LLM_VM_OPENAI_API_KEY\"), tools, verbose=4)\n conversation_history = []\n last = \"\"\n while True:\n inp = input(last+\"Human: \")\n return_value = label.run(inp, conv...
Agent(key, tools, verbose = 1)
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent.py", "retrieved_chunk": " # tools = [{'method': 'GET',\"description\":\"use this tool to find the price of stocks\",'args' : {\"url\":\"https://finnhub.io/api/v1/quote\",'params': { 'token' :'cfi1v29r01qq9nt1nu4gcfi1v29r01qq9nt1nu50'} },\"dyna...
""" This file has been temporarily repurposed as an interface for users to call any of the three agents (REBEL, BACKWARD_CHAINING, and FLAT) and interact with them. Running this file prompts the user to choose any of the agents and ask it questions. """ import llm_vm.agents.REBEL.agent as REBEL import llm_vm.agents.FLA...
elif model_choice == 2: tools = REBEL.buildExampleTools() agent = REBEL.Agent(key, tools, verbose = 1) pass mem = [] last = "" while True: inp = input(last+"Human: ") ret = agent.run(inp, mem) mem = ret[1] last = "AI: "+str(ret[0])+ "\n" if __name...
{ "context_start_lineno": 0, "file": "src/llm_vm/agents/agent_interface.py", "groundtruth_start_lineno": 46, "repository": "anarchy-ai-LLM-VM-83da960", "right_context_start_lineno": 47, "task_id": "project_cc_python/8398" }
{ "list": [ { "filename": "src/llm_vm/agents/FLAT/agent.py", "retrieved_chunk": " label = Agent(os.getenv(\"LLM_VM_OPENAI_API_KEY\"), tools, verbose=4)\n conversation_history = []\n last = \"\"\n while True:\n inp = input(last+\"Human: \")\n return_value = label.run(inp, conv...
Agent(key, tools, verbose=1)
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\t\t\t\tpos.size = pos['size']\n\t\t\t\topt = pos.op\n\t\t\t\topt.delta = pos['delta'] / opt.size\n\t\t\t\topt.gamma = pos['gamma'] / opt.size\n\t\t\t\topt.vega = pos['vega'] / opt.size\n\t\t\t\topt.theta = pos['theta'] / o...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.onPositionCreate(results) def fetch(self): self.window.progressBarFetch.setValue(0) self.fetches = [] curr = self.window.comboCurr.currentText() pctStrike = self.window.spinBoxStrikePercent.value() / 100.0 minExpiry = self.window.spinBoxMinExpiry.value() maxExpiry = self.window.spinBoxMaxExpiry.va...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 180, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 181, "task_id": "project_cc_python/8521" }
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\tdef getData(self, j, i):\n\t\tif j == 0:\n\t\t\tif i == 0:\n\t\t\t\treturn \"Instr\"\n\t\t\telif i == 1:\n\t\t\t\treturn \"Size\"\n\t\t\telif i == 2:\n\t\t\t\treturn \"Delta\"\n\t\t\telif i == 3:\n\t\t\t\treturn \"Gamma\"...
ticker(name)
{ "list": [ { "filename": "quickstart_finetune.py", "retrieved_chunk": " temperature=0.0,\n data_synthesis=True,\n finetune=True,)\nprint(response)\n# response = client.complete(prompt = \"Answer question Q. \",context=\"Q: ...
# import llm_vm.client as l import os, requests, json openai_key = os.getenv('LLM_VM_OPENAI_API_KEY') url = "http://localhost:3002/v1/complete" json_payload = {"prompt": "what is the economic situation in canada?", "context": "", "temperature": 0.0, "openai_key": openai...
print(response.text)
{ "context_start_lineno": 0, "file": "test_llm_vm.py", "groundtruth_start_lineno": 13, "repository": "anarchy-ai-LLM-VM-83da960", "right_context_start_lineno": 14, "task_id": "project_cc_python/8397" }
{ "list": [ { "filename": "quickstart_finetune.py", "retrieved_chunk": "# response = client.complete(prompt = \"Answer question Q. \",context=\"Q: What is the currency in myanmmar\",\n# openai_key=settings.openai_api_key,\n# temperature=0.0,\n# ...
post(url, data=json.dumps(json_payload))
{ "list": [ { "filename": "src/optarber/selection_data.py", "retrieved_chunk": "class SelectionData:\n\tdef __init__(self):\n\t\tself.positions = []\n\t\tself.cols = 10\n\tdef clear(self):\n\t\tself.positions = []\n\t\tself.cols = 10\n\tdef update(self, positions):\n\t\tself.positions = positions\n\td...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.position_model.endResetModel() self.window.tableViewPositions.resizeColumnsToContents() self.window.tableViewPositions.viewport().update() def onPositionData(self, positions): self.positions.update(positions) self.window.tableViewPositions.viewport().update() def disconnect(self): if self.client_...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 128, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 129, "task_id": "project_cc_python/8505" }
{ "list": [ { "filename": "src/optarber/selection_data.py", "retrieved_chunk": "\t\treturn len(self.positions) + 1\n\tdef getCols(self):\n\t\treturn self.cols\n\tdef getData(self, j, i):\n\t\tif j == 0:\n\t\t\tif i == 0:\n\t\t\t\treturn \"Instr\"\n\t\t\telif i == 1:\n\t\t\t\treturn \"Size\"\n\t\t\teli...
add(positions)
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " for op in self.fetches:\n if op.ask_price is not None and op.bid_price is not None:\n if (op.ask_price - op.bid_price) <= self.params.maxSpreadBps:\n option_dict[op.name] = o...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.results.fees += min(abs(pos.size * feeBps), abs(cost) * 0.125) self.results.net_income = -self.results.income - self.results.fees curr = self.window.comboCurr.currentText() if len(instrs) > 0: res = self.client_rest.getportfoliomargin(curr, instrs) self.results.margin = res['margin'] else: ...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 336, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 337, "task_id": "project_cc_python/8536" }
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " option_dict.pop(pos.op.name)\n option_data = list(option_dict.values())\n N = len(option_data)\n deltas = np.zeros(N)\n gammas = np.zeros(N)\n vegas = np.zeros(N)\n ...
income += cost
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": "import cvxpy as cvx\nimport numpy as np\nfrom deribit_option_position import DeribitPosition\nclass Optimizer:\n def __init__(self, params, fetches, positions):\n self.params = params\n self.fetches = fetches\n...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
now = dt.today() results = [] for pos in positions: name = pos['instrument_name'] instr = self.client_rest.getinstrument(name) expiry = self.timestamp_to_datetime(instr['expiration_timestamp']) days_left = (expiry - now).days size = pos['size'] opt = Option(name, instr['option_type'], days_left...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 163, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 164, "task_id": "project_cc_python/8519" }
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " for op in self.fetches:\n if op.ask_price is not None and op.bid_price is not None:\n if (op.ask_price - op.bid_price) <= self.params.maxSpreadBps:\n option_dict[op.name] = o...
getpositions(curr, "option")
{ "list": [ { "filename": "src/optarber/account_data.py", "retrieved_chunk": "\t\tself.maintenanceMargin = 0\n\t\tself.withdrawableFunds = 0\n\t\tself.PnL = 0\n\t\tself.delta = 0\n\t\tself.gamma = 0\n\t\tself.vega = 0\n\t\tself.theta = 0\n\t\tself.rows = 11\n\t\tself.cols = 2\n\tdef update(self, dict_...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.positions.add(positions) self.position_model.endResetModel() self.window.tableViewPositions.resizeColumnsToContents() self.window.tableViewPositions.viewport().update() def onPositionData(self, positions): self.positions.update(positions) self.window.tableViewPositions.viewport().update() def dis...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 127, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 128, "task_id": "project_cc_python/8504" }
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\tdef getData(self, j, i):\n\t\tif j == 0:\n\t\t\tif i == 0:\n\t\t\t\treturn \"Instr\"\n\t\t\telif i == 1:\n\t\t\t\treturn \"Size\"\n\t\t\telif i == 2:\n\t\t\t\treturn \"Delta\"\n\t\t\telif i == 3:\n\t\t\t\treturn \"Gamma\"...
beginResetModel()
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " cons.append(x <= self.params.maxUnit)\n cons.append(x >= 0)\n cons.append(y >= -self.params.maxUnit)\n cons.append(y <= 0)\n cons.append(cvx.sum(x + cvx.pos(p)) <= self.params.maxTotal)\n ...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.selection_model.endResetModel() def compute(self): params = self.create_optimiser_params() optim = Optimizer(params, self.fetches, self.positions.positions) selections = optim.compute() self.selection_model.beginResetModel() self.selections.update(selections) self.selection_model.endResetModel() ...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 291, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 292, "task_id": "project_cc_python/8530" }
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " sizes[0, idx] = pos.size / self.params.contract_size\n cons.append(p == np.asarray(sizes))\n for i in range(N):\n cons.append(x[0, i] <= askamounts[i])\n cons.append(y[0, i] ...
update([])
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\t\t\telif i == 1:\n\t\t\t\treturn pos.size\n\t\t\telif i == 2:\n\t\t\t\treturn pos.op.delta * pos.size\n\t\t\telif i == 3:\n\t\t\t\treturn pos.op.gamma * pos.size\n\t\t\telif i == 4:\n\t\t\t\treturn pos.op.vega * pos.size\...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
def create_optimiser_params(self): curr = self.window.comboCurr.currentText() params = OptimiseParams.create_default() if curr == 'BTC': params.contract_size = 0.1 else: params.contract_size = 1 params.currObjective = self.window.comboObjective.currentText() params.maxDeltaPct = self.window.spi...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 261, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 262, "task_id": "project_cc_python/8528" }
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\t\t\telse:\n\t\t\t\treturn 0", "score": 32.6999247743031 }, { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\tdef getData(self, j, i):\n\t\tif j == 0:\n\t\t\tif i == 0:\n\t\t\t\...
deleteLater()
{ "list": [ { "filename": "src/optarber/mainUI.py", "retrieved_chunk": " self.spinBoxStrikePercent.setProperty(\"value\", 10)\n self.spinBoxStrikePercent.setObjectName(\"spinBoxStrikePercent\")\n self.verticalLayout_9.addWidget(self.spinBoxStrikePercent)\n self.spinBoxMinEx...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
idxPrice = response[curr] now = dt.today() self.queryPos() self.fetchInstruments(now, curr, idxPrice, pctStrike, minExpiry, maxExpiry) self.window.progressBarFetch.setValue(len(self.subscribed) * 100.0 / self.counter) self.window.labelNumOfOptions.setText(str(self.counter) + " options") def timestamp_to_...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 190, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 191, "task_id": "project_cc_python/8522" }
{ "list": [ { "filename": "src/optarber/mainUI.py", "retrieved_chunk": " self.spinBoxMaxExpiry.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.spinBoxMaxExpiry.setProperty(\"value\", 10)\n self.spinBoxMaxExpiry.setObjectName(\"spinBoxMa...
getindex(curr)
{ "list": [ { "filename": "src/optarber/ccxt_test.py", "retrieved_chunk": "import ccxt\nimport configparser\nimport json\nif __name__ == '__main__':\n cfg = configparser.ConfigParser()\n cfg.read(\"config\\\\config.ini\")\n key = \"TEST\"\n api_key = cfg[key][\"api_key\"]\n api_secret =...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
QtCore.QTimer.singleShot(3000, self.authenticate) QtCore.QTimer.singleShot(6000, self.getChanges) def onMarketData(self, mkt_data): instr = mkt_data['instrument_name'] if instr not in self.subscribed: self.subscribed.add(instr) self.window.progressBarFetch.setVisible(False) self.window.progressBar...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 95, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 96, "task_id": "project_cc_python/8502" }
{ "list": [ { "filename": "src/optarber/ccxt_test.py", "retrieved_chunk": " exch.set_sandbox_mode(True)\n exch.quoteJsonNumbers = False\n response = exch.fetch2(\"get_portfolio_margins\", \"private\", params={\"currency\": \"BTC\"})\n print(response)", "score": 100.62186518723894 ...
connect(self, api_key, api_secret, ws_url)
{ "list": [ { "filename": "src/optarber/deribit_rest.py", "retrieved_chunk": " def getportfoliomargin(self, curr, instrs):\n options = {\n 'currency':curr, \n 'simulated_positions': json.dumps(instrs),\n 'add_positions': 'true'\n }\n response...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
minStrike = (1.0 - pctStrike) * idxPrice maxStrike = (1.0 + pctStrike) * idxPrice for instr in instrs: if instr['option_type'] == 'call' and instr['strike'] < idxPrice: continue if instr['option_type'] == 'put' and instr['strike'] > idxPrice: continue if instr['strike'] >= minStrike and instr...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 203, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 204, "task_id": "project_cc_python/8523" }
{ "list": [ { "filename": "src/optarber/deribit_rest.py", "retrieved_chunk": " return {}\n def getinstrument(self, instr):\n options = {\n 'instrument_name': instr,\n }\n response = self.call_api(\"get_instrument\", \"public\", options)\n if \"resul...
getinstruments(curr, "option")
{ "list": [ { "filename": "src/inn_service/infrastructure/handlers/base_handler.py", "retrieved_chunk": " self,\n settings: Settings,\n logger: AppLogger,\n rabbitmq_connection: RabbitConnectionManager\n ) -> None:\n self.settings = settings\n ...
from typing import Optional from logger import AppLogger from infrastructure.handlers.base_handler import BaseHandler from connection_managers.rabbitmq_connection_manager import RabbitConnectionManager from settings import Settings from services.inn_service import InnService from models.model import ClientDataDTO fro...
self.retry_times = self.settings.app_request_retry_times self.retry_sec = self.settings.app_request_retry_sec self.service = service def handler_name(self) -> str: return 'RequestHandler' def get_source_queue(self) -> str: return self.source_queue_name def get_use...
{ "context_start_lineno": 0, "file": "src/inn_service/infrastructure/handlers/request_handler.py", "groundtruth_start_lineno": 22, "repository": "DFilyushin-habr-project-inn-0465f4f", "right_context_start_lineno": 23, "task_id": "project_cc_python/8448" }
{ "list": [ { "filename": "src/inn_service/infrastructure/handlers/base_handler.py", "retrieved_chunk": " def handler_name(self) -> str:\n return 'BaseHandler'\n @abstractmethod\n def get_use_retry(self) -> bool:\n raise NotImplementedError\n def get_retry_ttl(self) -> int:\n...
settings.rabbitmq_source_queue_name
{ "list": [ { "filename": "src/inn_service/infrastructure/queue_manager/queue_manager.py", "retrieved_chunk": " except ValidationError as exc:\n error_message = f'Request body content error. {str(exc.errors())}'\n self.logger.error(error_message)\n ...
from typing import Optional from logger import AppLogger from infrastructure.handlers.base_handler import BaseHandler from connection_managers.rabbitmq_connection_manager import RabbitConnectionManager from settings import Settings from services.inn_service import InnService from models.model import ClientDataDTO fro...
response = await self.service.get_client_inn(client_data) if result_queue: json_message = response.dict() await self.rabbitmq_connection.send_data_in_queue(json_message, result_queue) return True
{ "context_start_lineno": 0, "file": "src/inn_service/infrastructure/handlers/request_handler.py", "groundtruth_start_lineno": 64, "repository": "DFilyushin-habr-project-inn-0465f4f", "right_context_start_lineno": 65, "task_id": "project_cc_python/8451" }
{ "list": [ { "filename": "src/inn_service/infrastructure/handlers/base_handler.py", "retrieved_chunk": " result_queue: Optional[str],\n count_retry: Optional[int] = 0\n ) -> bool:\n raise NotImplementedError", "score": 38.45924770403008 }, { "filena...
parse_obj(message)
{ "list": [ { "filename": "src/inn_service/infrastructure/queue_manager/queue_manager.py", "retrieved_chunk": " if result_queue:\n response = handler.get_error_response(request_id, error_message)\n await self._send_error_response(response, result_qu...
from typing import Optional from logger import AppLogger from infrastructure.handlers.base_handler import BaseHandler from connection_managers.rabbitmq_connection_manager import RabbitConnectionManager from settings import Settings from services.inn_service import InnService from models.model import ClientDataDTO fro...
return True
{ "context_start_lineno": 0, "file": "src/inn_service/infrastructure/handlers/request_handler.py", "groundtruth_start_lineno": 70, "repository": "DFilyushin-habr-project-inn-0465f4f", "right_context_start_lineno": 71, "task_id": "project_cc_python/8452" }
{ "list": [ { "filename": "src/inn_service/infrastructure/queue_manager/queue_manager.py", "retrieved_chunk": " if result_queue:\n response = handler.get_error_response(request_id, error_message)\n await self._send_error_response(response, result_qu...
rabbitmq_connection.send_data_in_queue(json_message, result_queue)
{ "list": [ { "filename": "src/inn_service/infrastructure/handlers/base_handler.py", "retrieved_chunk": " result_queue: Optional[str],\n count_retry: Optional[int] = 0\n ) -> bool:\n raise NotImplementedError", "score": 34.378235160119914 }, { "filen...
from typing import Optional from logger import AppLogger from infrastructure.handlers.base_handler import BaseHandler from connection_managers.rabbitmq_connection_manager import RabbitConnectionManager from settings import Settings from services.inn_service import InnService from models.model import ClientDataDTO fro...
return True if not request_id: raise HandlerNoRequestIdException self.logger.info(f'Get request {request_id} for response {result_queue}') client_data = RequestMqSerializer.parse_obj(message) response = await self.service.get_client_inn(client_data) ...
{ "context_start_lineno": 0, "file": "src/inn_service/infrastructure/handlers/request_handler.py", "groundtruth_start_lineno": 56, "repository": "DFilyushin-habr-project-inn-0465f4f", "right_context_start_lineno": 57, "task_id": "project_cc_python/8450" }
{ "list": [ { "filename": "src/inn_service/infrastructure/handlers/base_handler.py", "retrieved_chunk": " result_queue: Optional[str],\n count_retry: Optional[int] = 0\n ) -> bool:\n raise NotImplementedError", "score": 34.378235160119914 }, { "filen...
logger.warning(f'Request {request_id} was rejected by excess attempts {self.retry_times} times')
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\t\t\t\tpos.size = pos['size']\n\t\t\t\topt = pos.op\n\t\t\t\topt.delta = pos['delta'] / opt.size\n\t\t\t\topt.gamma = pos['gamma'] / opt.size\n\t\t\t\topt.vega = pos['vega'] / opt.size\n\t\t\t\topt.theta = pos['theta'] / o...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
else: res = self.client_rest.sell(pos.op.name, abs(pos.size), pos.op.bid_price) if len(opts) > 0: pos = opts[-1] del opts[-1] if pos.size > 0: res = self.client_rest.buy(pos.op.name, pos.size, pos.op.ask_price) else: res = self.client_rest.sell(pos.op.name, abs(pos.size), pos....
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 435, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 436, "task_id": "project_cc_python/8538" }
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " for i, op in enumerate(option_data):\n if res[0, i] != 0:\n p = DeribitPosition(op, res[0, i])\n selections.append(p)\n return selections\n def _calcula...
buy(pos.op.name, pos.size, pos.op.ask_price)
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " for op in self.fetches:\n if op.ask_price is not None and op.bid_price is not None:\n if (op.ask_price - op.bid_price) <= self.params.maxSpreadBps:\n option_dict[op.name] = o...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
self.results.net_income = -self.results.income - self.results.fees curr = self.window.comboCurr.currentText() if len(instrs) > 0: res = self.client_rest.getportfoliomargin(curr, instrs) self.results.margin = res['margin'] else: self.results.margin = 0 minExpiry = 10000000 for pos in positions:...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 337, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 338, "task_id": "project_cc_python/8537" }
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " option_dict.pop(pos.op.name)\n option_data = list(option_dict.values())\n N = len(option_data)\n deltas = np.zeros(N)\n gammas = np.zeros(N)\n vegas = np.zeros(N)\n ...
fees += min(abs(pos.size * feeBps), abs(cost) * 0.125)
{ "list": [ { "filename": "src/optarber/optimizer.py", "retrieved_chunk": " for op in self.fetches:\n if op.ask_price is not None and op.bid_price is not None:\n if (op.ask_price - op.bid_price) <= self.params.maxSpreadBps:\n option_dict[op.name] = o...
import configparser from datetime import datetime as dt import opstrat from account_data import AccountData from image_viewer import ImageViewer from position_data import PositionData from results_data import Results from selection_data import SelectionData from account_model import AccountModel from optimise_params im...
if len(opts) > 0: pos = opts[-1] del opts[-1] if pos.size > 0: res = self.client_rest.buy(pos.op.name, pos.size, pos.op.ask_price) else: res = self.client_rest.sell(pos.op.name, abs(pos.size), pos.op.bid_price) if 'trades' in res: print(len(res['trades'])) else: print(...
{ "context_start_lineno": 0, "file": "src/optarber/optionAtilla.py", "groundtruth_start_lineno": 437, "repository": "satyapravin-Deribit-Option-Arb-c6fead7", "right_context_start_lineno": 438, "task_id": "project_cc_python/8539" }
{ "list": [ { "filename": "src/optarber/position_data.py", "retrieved_chunk": "\tdef getData(self, j, i):\n\t\tif j == 0:\n\t\t\tif i == 0:\n\t\t\t\treturn \"Instr\"\n\t\t\telif i == 1:\n\t\t\t\treturn \"Size\"\n\t\t\telif i == 2:\n\t\t\t\treturn \"Delta\"\n\t\t\telif i == 3:\n\t\t\t\treturn \"Gamma\"...
sell(pos.op.name, abs(pos.size), pos.op.bid_price)
{ "list": [ { "filename": "src/walkjump/model/_noise_ebm.py", "retrieved_chunk": " },\n }\n def xhat(self, y: torch.Tensor) -> torch.Tensor:\n return self.denoise_model.xhat(y)\n def compute_loss(self, batch: AbBatch) -> torch.Tensor:\n random_seeds = random_discr...
import torch from walkjump.constants import LENGTH_FV_HEAVY_AHO, LENGTH_FV_LIGHT_AHO, TOKENS_AHO def isotropic_gaussian_noise_like(x: torch.Tensor, sigma: float) -> torch.Tensor: return sigma * torch.randn_like(x.float()) def random_discrete_seeds( n_seeds: int, n_tokens: int = len(TOKENS_AHO), see...
else: return random_seeds
{ "context_start_lineno": 0, "file": "src/walkjump/utils/_noise.py", "groundtruth_start_lineno": 17, "repository": "Genentech-walk-jump-3cfaa37", "right_context_start_lineno": 18, "task_id": "project_cc_python/8424" }
{ "list": [ { "filename": "src/walkjump/model/_noise_ebm.py", "retrieved_chunk": " )\n y_fake = walk(random_seeds, self, self.training_sampler_fn)\n y_real = self.apply_noise(batch.x)\n energy_real, _ = self.model(y_real)\n energy_fake, _ = self.model(y_fake)\n ...
nn.functional.one_hot(random_seeds, num_classes=n_tokens)
{ "list": [ { "filename": "src/walkjump/data/_dataset.py", "retrieved_chunk": " alphabet_or_token_list: InitVar[LabelEncoder | list[str]] = ALPHABET_AHO\n alphabet: LabelEncoder = field(init=False)\n def __post_init__(self, alphabet_or_token_list: LabelEncoder | list[str]):\n self.alph...
import re import torch from sklearn.preprocessing import LabelEncoder def tokenize_string(string: str, alphabet: list[str]) -> list[str]: """ Tokenize a string element of alphabet* into a list. Parameters ---------- string: str Element of the language alphabet*, i.e., it is a str...
if onehot: size = len(alphabet.classes_) tensor = torch.nn.functional.one_hot(tensor, num_classes=size) return tensor def token_string_from_tensor( tensor: torch.Tensor, alphabet: LabelEncoder, from_logits: bool = True, ) -> list[str]: """Convert tensor representation of sequ...
{ "context_start_lineno": 0, "file": "src/walkjump/utils/_tokenize.py", "groundtruth_start_lineno": 32, "repository": "Genentech-walk-jump-3cfaa37", "right_context_start_lineno": 33, "task_id": "project_cc_python/8426" }
{ "list": [ { "filename": "src/walkjump/data/_dataset.py", "retrieved_chunk": " return len(self.df)\n def __getitem__(self, index: int) -> torch.Tensor:\n row = self.df.loc[index]\n tensor_h = token_string_to_tensor(row.fv_heavy_aho, self.alphabet)\n tensor_l = token_str...
from_numpy(alphabet.transform(tokenized)).long()
{ "list": [ { "filename": "src/walkjump/model/arch/_layers.py", "retrieved_chunk": " self.chain_length = chain_length\n self.vocab_size = vocab_size\n self.hidden_features = hidden_features\n self.kernel_sizes = kernel_sizes\n self.input_seq = nn.Linear(vocab_size * ...
from dataclasses import dataclass from functools import cached_property import torch from walkjump.constants import TOKENS_AHO @dataclass class AbBatch: batch_tensor: torch.Tensor """(b, L)-shaped tensor of sequences""" vocab_size: int = len(TOKENS_AHO) @classmethod def from_tensor_pylist( ...
{ "context_start_lineno": 0, "file": "src/walkjump/data/_batch.py", "groundtruth_start_lineno": 24, "repository": "Genentech-walk-jump-3cfaa37", "right_context_start_lineno": 25, "task_id": "project_cc_python/8418" }
{ "list": [ { "filename": "src/walkjump/utils/_noise.py", "retrieved_chunk": " random_seeds = torch.randint(0, n_tokens, (n_seeds, seed_length))\n if onehot:\n return torch.nn.functional.one_hot(random_seeds, num_classes=n_tokens)\n else:\n return random_seeds", "score": 2...
nn.functional.one_hot(self.batch_tensor, num_classes=self.vocab_size).float()
{ "list": [ { "filename": "src/walkjump/data/_datamodule.py", "retrieved_chunk": " case _:\n raise ValueError(f\"Unreognized 'stage': {stage}\")\n def _make_dataloader(self, partition: Literal[\"train\", \"val\", \"test\"]) -> DataLoader:\n df = self.dataset[self.da...
from dataclasses import InitVar, dataclass, field import pandas as pd import torch from sklearn.preprocessing import LabelEncoder from torch.utils.data import Dataset from walkjump.constants import ALPHABET_AHO from walkjump.utils import token_string_to_tensor @dataclass class AbDataset(Dataset): df: pd.DataFra...
{ "context_start_lineno": 0, "file": "src/walkjump/data/_dataset.py", "groundtruth_start_lineno": 32, "repository": "Genentech-walk-jump-3cfaa37", "right_context_start_lineno": 33, "task_id": "project_cc_python/8420" }
{ "list": [ { "filename": "src/walkjump/data/_datamodule.py", "retrieved_chunk": " collate_fn=AbBatch.from_tensor_pylist,\n )\n def train_dataloader(self) -> DataLoader:\n return self._make_dataloader(\"train\")\n def val_dataloader(self) -> DataLoader:\n return s...
cat([tensor_h, tensor_l])
{ "list": [ { "filename": "src/walkjump/sampling/_walkjump.py", "retrieved_chunk": " \"\"\"\n return torch.nn.functional.one_hot(\n torch.nn.utils.rnn.pad_sequence(\n [token_string_to_tensor(seed_i, ALPHABET_AHO, onehot=False) for seed_i in seeds],\n batch_first=True...
import re import torch from sklearn.preprocessing import LabelEncoder def tokenize_string(string: str, alphabet: list[str]) -> list[str]: """ Tokenize a string element of alphabet* into a list. Parameters ---------- string: str Element of the language alphabet*, i.e., it is a str...
return tensor def token_string_from_tensor( tensor: torch.Tensor, alphabet: LabelEncoder, from_logits: bool = True, ) -> list[str]: """Convert tensor representation of sequence to list of string Parameters ---------- tensor: torch.Tensor Input tensor from_logits: bool ...
{ "context_start_lineno": 0, "file": "src/walkjump/utils/_tokenize.py", "groundtruth_start_lineno": 36, "repository": "Genentech-walk-jump-3cfaa37", "right_context_start_lineno": 37, "task_id": "project_cc_python/8427" }
{ "list": [ { "filename": "src/walkjump/data/_dataset.py", "retrieved_chunk": " return len(self.df)\n def __getitem__(self, index: int) -> torch.Tensor:\n row = self.df.loc[index]\n tensor_h = token_string_to_tensor(row.fv_heavy_aho, self.alphabet)\n tensor_l = token_str...
nn.functional.one_hot(tensor, num_classes=size)
{ "list": [ { "filename": "src/walkjump/utils/_noise.py", "retrieved_chunk": "import torch\nfrom walkjump.constants import LENGTH_FV_HEAVY_AHO, LENGTH_FV_LIGHT_AHO, TOKENS_AHO\ndef isotropic_gaussian_noise_like(x: torch.Tensor, sigma: float) -> torch.Tensor:\n return sigma * torch.randn_like(x.floa...
from dataclasses import dataclass from functools import cached_property import torch from walkjump.constants import TOKENS_AHO @dataclass class AbBatch: batch_tensor: torch.Tensor """(b, L)-shaped tensor of sequences""" vocab_size: int = len(TOKENS_AHO) @classmethod def from_tensor_pylist( ...
return cls(packed_batch, vocab_size=vocab_size) @cached_property def x(self) -> torch.Tensor: return torch.nn.functional.one_hot(self.batch_tensor, num_classes=self.vocab_size).float()
{ "context_start_lineno": 0, "file": "src/walkjump/data/_batch.py", "groundtruth_start_lineno": 19, "repository": "Genentech-walk-jump-3cfaa37", "right_context_start_lineno": 20, "task_id": "project_cc_python/8417" }
{ "list": [ { "filename": "src/walkjump/utils/_noise.py", "retrieved_chunk": " random_seeds = torch.randint(0, n_tokens, (n_seeds, seed_length))\n if onehot:\n return torch.nn.functional.one_hot(random_seeds, num_classes=n_tokens)\n else:\n return random_seeds", "score": 2...
stack(inputs, dim=0)
{ "list": [ { "filename": "src/dataset/wmt_dataset.py", "retrieved_chunk": " version: str = \"16\",\n src_lan: str = \"ro\",\n tgt_lan: str = \"en\",\n hugginface_tokenizer=None,\n split: str = None,\n ):\n self.src_lan = src_lan\n self.tgt_lan = tgt...
import torch from torch.utils.data import Dataset import datasets from src.utils.utils import retrieve_map_languages_flores, clean_text import typing as t class Flores(Dataset): def __init__( self, src_lan: str = "ro", tgt_lan: str = "en", hugginface_tokenizer=None, split:...
self.tgt_lan = retrieve_map_languages_flores(tgt_lan).lower()[:3] if "test" in split: split = "dev" + split self.translation_dataset_src = datasets.load_dataset( "gsarti/flores_101", self.src_lan, split=split ) self.translation_dataset_tgt = datasets.lo...
{ "context_start_lineno": 0, "file": "src/dataset/flores_dataset.py", "groundtruth_start_lineno": 18, "repository": "teelinsan-parallel-decoding-b16a009", "right_context_start_lineno": 19, "task_id": "project_cc_python/8545" }
{ "list": [ { "filename": "src/dataset/wmt_dataset.py", "retrieved_chunk": " if src_lan == \"en\":\n source2target = \"{}-{}\".format(self.tgt_lan, self.src_lan)\n else:\n source2target = \"{}-{}\".format(self.src_lan, self.tgt_lan)\n if version == \"19\" and...
lower()[:3]
{ "list": [ { "filename": "src/ipi/stopping_condition.py", "retrieved_chunk": " assert past_tensor.shape == current_tensor.shape\n if torch.equal(past_tensor, current_tensor):\n tensor = current_tensor\n if eos is not None:\n if eos in current_tensor[0]:\n ...
from typing import Dict, Optional import torch from transformers import MBartForConditionalGeneration from src.ipi import stopping_condition as sc from src.utils.utils import get_logits_preprocessor PREC_GOLD_AUTOREGRESSIVE: Dict[str, Optional[torch.Tensor]] = {"input_ids": None, "gold": None} PREC_LOGISTS_PREPROCES...
@staticmethod def limit_past_key_values(past_key_values, limit): return sc.limit_past_key_values(past_key_values, limit) @staticmethod def trig_eos(tensor, eos_token_id, init_tensor, base_value): if tensor[:, 0].item() == eos_token_id: return init_tensor[:, : base_value + ...
{ "context_start_lineno": 0, "file": "src/ipi/decoders/mt_decoding.py", "groundtruth_start_lineno": 105, "repository": "teelinsan-parallel-decoding-b16a009", "right_context_start_lineno": 106, "task_id": "project_cc_python/8543" }
{ "list": [ { "filename": "src/ipi/stopping_condition.py", "retrieved_chunk": " if eos in tensor[0]:\n pos = (tensor[0] == eos).nonzero(as_tuple=True)[0]\n if pos.shape[0] > 1:\n pos = pos[0].item()\n else:\n pos = pos.item()\n return pos\n else:...
stopping_criterion(past_tensor, current_tensor, eos)
{ "list": [ { "filename": "src/bench.py", "retrieved_chunk": " def __init__(\n self,\n dataset: Dataset,\n decoders,\n src_lang,\n tgt_lang,\n compare_to: str = \"autoregressive\",\n result_dir: str = None,\n de...
import hydra from transformers import ( AutoModelForSeq2SeqLM, AutoTokenizer, MBartForConditionalGeneration, ) from src.bench import MTBenchmarker from src.dataset.flores_dataset import Flores from src.dataset.ittb_dataset import Ittb from src.dataset.iwslt_dataset import Iwslt from src.dataset.wmt_dataset...
@hydra.main(config_path="conf", config_name="config", version_base="1.1") def main(cfg): tokenizer = load_tokenizer(cfg.model) model = load_model(cfg.model) dataset = load_dataset(tokenizer, cfg.dataset) if "benchmark" in cfg.task: compute_benchmark(cfg, tokenizer, dataset, model) elif...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 261, "repository": "teelinsan-parallel-decoding-b16a009", "right_context_start_lineno": 262, "task_id": "project_cc_python/8541" }
{ "list": [ { "filename": "src/bench.py", "retrieved_chunk": " ):\n self.dataset = dataset\n self.decoders = decoders\n self.device = device\n self.debug = debug\n self.compare_to = compare_to\n self.src_lang = src_lang\n self.tgt_lang = tgt_lang\n ...
compute_total_time()
{ "list": [ { "filename": "src/utils/beam_search.py", "retrieved_chunk": " early_stopping,\n batch_size,\n device,\n result_dir,\n ):\n self.num_beams = num_beams\n self.no_repeat_ngram_size = no_repeat_ngram_size\n self.early_stoppin...
import hydra from transformers import ( AutoModelForSeq2SeqLM, AutoTokenizer, MBartForConditionalGeneration, ) from src.bench import MTBenchmarker from src.dataset.flores_dataset import Flores from src.dataset.ittb_dataset import Ittb from src.dataset.iwslt_dataset import Iwslt from src.dataset.wmt_dataset...
def load_decoders(cfg, tokenizer, model, initializer): decoders = [] for decoder in cfg.decoder.decoders: if decoder == "autoregressive": dec = AutoregressiveDecoder( tokenizer=tokenizer, model=model, initializer=initializer, ...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 190, "repository": "teelinsan-parallel-decoding-b16a009", "right_context_start_lineno": 191, "task_id": "project_cc_python/8540" }
{ "list": [ { "filename": "src/utils/beam_search.py", "retrieved_chunk": " self.dataset = dataset\n self.initializer = initializer\n self.decoder = decoder\n self.tokenizer = dataset.tokenizer\n self.model = model\n model.eval().to(self.device)\n self.m...
compute_beam_search(cfg)
{ "list": [ { "filename": "src/extraction_benchmark/extractors/boilernet/net/misc/util.py", "retrieved_chunk": "#! /usr/bin/python3\nimport random\nimport os\n# everything that is a child of one of these tags is considered boilerplate and hence ignored by the\n# classifier\nTAGS_TO_IGNORE = {'head', '...
#! /usr/bin/python3 import os import argparse import pickle import json from collections import defaultdict import nltk import numpy as np import tensorflow as tf from bs4 import BeautifulSoup, NavigableString from tqdm import tqdm from .misc import util def get_leaves(node, tag_list=[], label=0): """Return a...
int_map['<UNK>'] = 0 return int_map def get_doc_inputs(docs, word_map, tag_map): """Transform "docs" into the input format accepted by the classifier.""" def _int64_feature(l): """Return an int64_list.""" return tf.train.Feature(int64_list=tf.train.Int64List(value=l)) for doc in...
{ "context_start_lineno": 0, "file": "src/extraction_benchmark/extractors/boilernet/net/preprocess.py", "groundtruth_start_lineno": 103, "repository": "chatnoir-eu-web-content-extraction-benchmark-221b650", "right_context_start_lineno": 104, "task_id": "project_cc_python/8548" }
{ "list": [ { "filename": "src/extraction_benchmark/extractors/bte.py", "retrieved_chunk": " if tag in HEADER_FIND_TAGS:\n if tag_h_l:\n result.append(HEADER_REPLACE_TAG)\n else:\n result.append(PAR_REPLACE_TAG)\n ...
get_int_map(l, offset=1)
{ "list": [ { "filename": "src/extraction_benchmark/extractors/boilernet/net/preprocess.py", "retrieved_chunk": "def main():\n ap = argparse.ArgumentParser()\n ap.add_argument('DIRS', nargs='+', help='A list of directories containing the HTML files')\n ap.add_argument('-s', '--split_dir', hel...
import argparse import os from tqdm import tqdm from bs4 import BeautifulSoup, NavigableString, Comment import util def process_bp(doc): """Process HTML files annotated by BoilerPipe. We ignore nodes labeled as "comment".""" for node in doc.find_all(attrs={'__prediction': True}): node['__boilernet_i...
try: with open(f, 'rb') as hfile: doc = BeautifulSoup(hfile, features='html5lib') # for some reason, parsing malformed HTML twice works better doc2 = BeautifulSoup(doc.prettify(), features='html5lib') process(doc2, dataset_functions[args.DATASET])...
{ "context_start_lineno": 0, "file": "src/extraction_benchmark/extractors/boilernet/net/misc/prepare_dataset.py", "groundtruth_start_lineno": 92, "repository": "chatnoir-eu-web-content-extraction-benchmark-221b650", "right_context_start_lineno": 93, "task_id": "project_cc_python/8551" }
{ "list": [ { "filename": "src/extraction_benchmark/extractors/boilernet/net/preprocess.py", "retrieved_chunk": " filenames = []\n for d in args.DIRS:\n filenames.extend(util.get_filenames(d))\n data, tags, words = parse(filenames)\n tags = get_vocabulary(tags, args.num_tags)\n w...
get_filenames(args.INPUT, '.html')):
{ "list": [ { "filename": "dataset/dgl_datasets/dgl_dataset.py", "retrieved_chunk": " [N, N, edge_int_feature.shape[1]], dtype=torch.long\n )\n attn_edge_type[\n edge_index[0].long(), edge_index[1].long()\n ] = convert_to_single_emb(edge_int_feature)\n ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch import numpy as np import torch_geometric from ogb.graphproppred import PygGraphPropPredDataset from ogb.lsc.pcqm4mv2_pyg import PygPCQM4Mv2Dataset from functools import lru_cache import pyximport import torch.distributed as dist py...
max_dist = np.amax(shortest_path_result) edge_input = algos.gen_edge_input(max_dist, path, attn_edge_type.numpy()) spatial_pos = torch.from_numpy((shortest_path_result)).long() attn_bias = torch.zeros([N + 1, N + 1], dtype=torch.float) # with graph token # combine item.x = x item.edge_fe...
{ "context_start_lineno": 0, "file": "dataset/wrapper.py", "groundtruth_start_lineno": 45, "repository": "czczup-GPTrans-1f6f651", "right_context_start_lineno": 46, "task_id": "project_cc_python/8570" }
{ "list": [ { "filename": "dataset/dgl_datasets/dgl_dataset.py", "retrieved_chunk": " attn_bias = torch.zeros([N + 1, N + 1], dtype=torch.float) # with graph token\n pyg_graph = PYGGraph()\n pyg_graph.x = convert_to_single_emb(node_int_feature)\n pyg_graph.adj = dense_adj\...
floyd_warshall(adj.numpy())
{ "list": [ { "filename": "dataset/build.py", "retrieved_chunk": " print(f\"local rank {config.LOCAL_RANK} / global rank {dist.get_rank()}\"\n f\"successfully build train dataset, with #samples: {len(dataset_train)}\")\n dataset_val = BatchedDataDataset(dataset.dataset_val, config.DATA....
import os import time import random import argparse import datetime import numpy as np import subprocess import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from timm.utils import ModelEma from timm.utils import AverageMeter from config import get_config from models import build_model fr...
model = build_model(config) model.cuda() logger.info(str(model)) # build optimizer optimizer = build_optimizer(config, model) if config.AMP_OPT_LEVEL != "O0": config.defrost() if has_native_amp: config.native_amp = True use_amp = 'native' config....
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 108, "repository": "czczup-GPTrans-1f6f651", "right_context_start_lineno": 109, "task_id": "project_cc_python/8565" }
{ "list": [ { "filename": "dataset/build.py", "retrieved_chunk": " num_tasks = dist.get_world_size()\n global_rank = dist.get_rank()\n if dataset_train is not None:\n sampler_train = torch.utils.data.DistributedSampler(\n dataset_train,\n num_replicas=num_tasks,\n...
info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}")
{ "list": [ { "filename": "utils.py", "retrieved_chunk": " 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'lr_scheduler': lr_scheduler.state_dict(),\n 'epoch': epoch,\n 'config': config\n }\n if model_ema is not None:\n save_state[...
import os import time import random import argparse import datetime import numpy as np import subprocess import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from timm.utils import ModelEma from timm.utils import AverageMeter from config import get_config from models import build_model fr...
if dist.get_rank() == 0 and (epoch % config.SAVE_FREQ == 0 or epoch == (config.TRAIN.EPOCHS - 1)): save_checkpoint(config, epoch, model_without_ddp, optimizer, lr_scheduler, loss_scaler, logger, best_performance=best_performance, best_performa...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 219, "repository": "czczup-GPTrans-1f6f651", "right_context_start_lineno": 220, "task_id": "project_cc_python/8568" }
{ "list": [ { "filename": "utils.py", "retrieved_chunk": " if best_performance is not None:\n save_state['best_performance'] = best_performance\n if best_performance_ema is not None:\n save_state['best_performance_ema'] = best_performance_ema\n if config.AMP_OPT_LEVEL != 'O0':\n...
consolidate_state_dict(to=0)
{ "list": [ { "filename": "utils.py", "retrieved_chunk": " if 'best_performance_ema' in checkpoint:\n best_performance_ema = checkpoint['best_performance_ema']\n if 'ema_decay' in checkpoint:\n model_ema.decay = checkpoint['ema_decay']\n return best_performance_ema\ndef load_che...
import os import time import random import argparse import datetime import numpy as np import subprocess import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from timm.utils import ModelEma from timm.utils import AverageMeter from config import get_config from models import build_model fr...
config.defrost() config.MODEL.RESUME = resume_file config.freeze() logger.info(f'auto resuming from {resume_file}') else: logger.info(f'no checkpoint found in {config.OUTPUT}, ignoring auto resume') # set resume and pretrain if config.MODEL.R...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 170, "repository": "czczup-GPTrans-1f6f651", "right_context_start_lineno": 171, "task_id": "project_cc_python/8567" }
{ "list": [ { "filename": "utils.py", "retrieved_chunk": " checkpoint = torch.hub.load_state_dict_from_url(config.MODEL.RESUME,\n map_location='cpu',\n check_hash=True)\n else:\n ...
warning(f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}")