id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
2,460
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list, extract_json from checkov.terraform.image_referencer.base_provider import BaseTerraformProv...
null
2,461
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list, extract_json from checkov.terraform.image_referencer.base_provider import BaseTerraformProv...
null
2,462
from __future__ import annotations import json import logging import os from collections import defaultdict from pathlib import Path from typing import Optional, Dict, Mapping, Set, Tuple, Callable, Any, List, cast, TYPE_CHECKING, overload import hcl2 from checkov.common.parallelizer.parallel_runner import parallel_run...
null
2,463
from __future__ import annotations import json import logging import os from collections import defaultdict from pathlib import Path from typing import Optional, Dict, Mapping, Set, Tuple, Callable, Any, List, cast, TYPE_CHECKING, overload import hcl2 from checkov.common.parallelizer.parallel_runner import parallel_run...
null
2,464
from __future__ import annotations import json import logging import os from collections import defaultdict from pathlib import Path from typing import Optional, Dict, Mapping, Set, Tuple, Callable, Any, List, cast, TYPE_CHECKING, overload import hcl2 from checkov.common.parallelizer.parallel_runner import parallel_run...
Load JSON or HCL, depending on filename. :return: None if the file can't be loaded
2,465
from __future__ import annotations import json import logging import os import re from pathlib import Path from typing import List, Callable, TYPE_CHECKING from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.util.file_utils import read_file_with_any_encoding from checkov.common.u...
null
2,466
from __future__ import annotations import re from typing import List, Dict, Optional, cast, Callable from checkov.common.packaging import version VERSION_REGEX = re.compile(r"^(?P<operator>=|!=|>=|>|<=|<|~>)?\s*(?P<version>[\d.]+-?\w*)$") class VersionConstraint: """ A class representing a module version. Enabl...
:param raw_version: A string representation of a version, e.g: "~> v1.2.3" :return: VersionConstraint instance
2,467
from __future__ import annotations import re from typing import List, Dict, Optional, cast, Callable from checkov.common.packaging import version The provided code snippet includes necessary dependencies for implementing the `order_versions_in_descending_order` function. Write a Python function `def order_versions_in_...
:param versions_strings: array of string versions: ["v1.2.3", "v1.2.4"...] :return: A sorted array of versions in descending order
2,468
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,469
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,470
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,471
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,472
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,473
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,474
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,475
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,476
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,477
from __future__ import annotations import json import logging from collections.abc import Hashable from typing import Dict, List, Union, Any, Callable from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import convert_str_to_bool from checkov.common.util.parser_ut...
null
2,478
from __future__ import annotations from collections import defaultdict import json import logging import os from typing import Dict, List, Tuple, Any from charset_normalizer import from_fp from checkov.terraform.context_parsers.registry import parser_registry from checkov.terraform.plan_parser import parse_tf_plan, TF_...
null
2,479
from __future__ import annotations from collections import defaultdict import json import logging import os from typing import Dict, List, Tuple, Any from charset_normalizer import from_fp from checkov.terraform.context_parsers.registry import parser_registry from checkov.terraform.plan_parser import parse_tf_plan, TF_...
null
2,480
from __future__ import annotations from collections import defaultdict import json import logging import os from typing import Dict, List, Tuple, Any from charset_normalizer import from_fp from checkov.terraform.context_parsers.registry import parser_registry from checkov.terraform.plan_parser import parse_tf_plan, TF_...
return resource id with the last module in the address example: from address='module.name1.module.name2.type.name' return 'module: module.name2.type.name'
2,481
from __future__ import annotations import logging import subprocess def get_kustomize_version(kustomize_command: str) -> str | None: try: proc = subprocess.run([kustomize_command, "version"], capture_output=True) # nosec version_output = proc.stdout.decode("utf-8") if "Version:" in versio...
null
2,482
from __future__ import annotations import logging import subprocess def get_kubectl_version(kubectl_command: str) -> float | None: try: proc = subprocess.run([kubectl_command, "version", "--client=true"], capture_output=True) # nosec version_output = proc.stdout.decode("utf-8") if "Client...
null
2,483
from __future__ import annotations import io import logging import multiprocessing import os import pathlib import platform import shutil import subprocess import tempfile import yaml from typing import Optional, Dict, Any, TextIO, TYPE_CHECKING from checkov.common.graph.graph_builder import CustomAttributes from chec...
null
2,484
import hmac from hashlib import sha1, sha256 import os from google.cloud import secretmanager PROJECT_NAME = os.environ.get("PROJECT_NAME") def get_secret(project_name, secret_name, version_num): """ Returns secret payload from Cloud Secret Manager """ try: client = secretmanager.SecretManagerSe...
Verifies that the signature received from the github event is accurate
2,485
import hmac from hashlib import sha1, sha256 import os from google.cloud import secretmanager PROJECT_NAME = os.environ.get("PROJECT_NAME") def get_secret(project_name, secret_name, version_num): """ Returns secret payload from Cloud Secret Manager """ try: client = secretmanager.SecretManagerSe...
Verifies that the signature received from the circleci event is accurate
2,486
import hmac from hashlib import sha1, sha256 import os from google.cloud import secretmanager PROJECT_NAME = os.environ.get("PROJECT_NAME") def get_secret(project_name, secret_name, version_num): """ Returns secret payload from Cloud Secret Manager """ try: client = secretmanager.SecretManagerSe...
Verifies that the signature received from the pagerduty event is accurate
2,487
import hmac from hashlib import sha1, sha256 import os from google.cloud import secretmanager PROJECT_NAME = os.environ.get("PROJECT_NAME") def get_secret(project_name, secret_name, version_num): """ Returns secret payload from Cloud Secret Manager """ try: client = secretmanager.SecretManagerSe...
Verifies that the token received from the event is accurate
2,488
import json import os import sys from flask import abort, Flask, request from google.cloud import pubsub_v1 import sources def publish_to_pubsub(source, msg, headers): """ Publishes the message to Cloud Pub/Sub """ try: publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic...
Receives event data from a webhook, checks if the source is authorized, checks if the signature is verified, and then sends the data to Pub/Sub.
2,489
import hashlib import json from google.cloud import bigquery def is_unique(client, signature): sql = "SELECT signature FROM four_keys.events_raw WHERE signature = '%s'" query_job = client.query(sql % signature) results = query_job.result() return not results.total_rows def insert_row_into_bigquery(even...
null
2,490
import hashlib import json from google.cloud import bigquery def is_unique(client, signature): sql = "SELECT signature FROM four_keys.events_raw WHERE signature = '%s'" query_job = client.query(sql % signature) results = query_job.result() return not results.total_rows def insert_row_into_events_enrich...
null
2,491
import hashlib import json from google.cloud import bigquery def create_unique_id(msg): hashed = hashlib.sha1(bytes(json.dumps(msg), "utf-8")) return hashed.hexdigest()
null
2,492
def flatten(d, sep="_"): obj = {} def recurse(t, parent_key=""): if isinstance(t, list): for i in range(len(t)): recurse(t[i], parent_key + sep + str(i) if parent_key else str(i)) elif isinstance(t, dict): for k, v in t.items(): recurse(v, ...
null
2,493
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def make_changes(num_changes, vcs, event_timespan, before=None): """Make a single ...
Make a lit of changesets of length ``num_event`` Args: num_events (int): the number of changesets to generate vcs: the version control system being used (options include github or gitlab event_timespan: time duration (in seconds) of timestamps of generated events num_changes: number of changes per changeset, defaults t...
2,494
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen The provided code snippet includes necessary dependencies for implementing the `make_...
Make individual change from a changeset Args: changeset: Changeset to make individual change from vcs: the version control system being used (options include github or gitlab Returns:
2,495
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def create_github_deploy_event(change): deployment = { "deployment_status...
null
2,496
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def create_gitlab_pipeline_event(changes): pipeline = None checkout_sha = cha...
null
2,497
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def create_gitlab_deploy_event(changes, deploy_id=None): deployment = None ch...
null
2,498
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def make_github_issue(root_cause): event = { "issue": { "crea...
null
2,499
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def make_gitlab_issue(changes): issue = None checkout_sha = changes["checkout...
null
2,500
from __future__ import annotations import argparse import datetime import hmac import json import math import os import random import secrets import time import sys from hashlib import sha1 from urllib.request import Request, urlopen def make_webhook_request(vcs, webhook_url, secret, event_type, data, token=None): ...
null
2,501
import base64 import os import json import shared from flask import Flask, request def process_new_source_event(msg): metadata = json.loads(base64.b64decode(msg["data"]).decode("utf-8").strip()) # [TODO: Parse the msg data to map to the event object below] new_source_event = { "event_type": "event_t...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,502
import base64 import os import json import shared from flask import Flask, request def process_argocd_event(msg): metadata = json.loads(base64.b64decode(msg["data"]).decode("utf-8").strip()) # Unique hash for the event signature = shared.create_unique_id(msg) argocd_event = { "event_type": "depl...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,503
import base64 import os import json import shared from flask import Flask, request def process_cloud_build_event(attr, msg): event_type = "build" e_id = attr["buildId"] # Unique hash for the event signature = shared.create_unique_id(msg) # Payload metadata = json.loads(base64.b64decode(msg["data...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,504
import base64 import os import json import shared from flask import Flask, request def process_circleci_event(headers, msg): event_type = headers["Circleci-Event-Type"] signature = headers["Circleci-Signature"] metadata = json.loads(base64.b64decode(msg["data"]).decode("utf-8").strip()) types = {"workfl...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,505
import base64 import os import json import shared from flask import Flask, request def process_pagerduty_event(msg): metadata = json.loads(base64.b64decode(msg["data"]).decode("utf-8").strip()) print(f"Metadata after decoding {metadata}") # Unique hash for the event signature = shared.create_unique_id(m...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,506
import base64 import os import json import shared from cloudevents.http import from_http, to_json from flask import Flask, request def process_tekton_event(headers, msg): data = base64.b64decode(msg["data"]).decode("utf-8").strip() cloud_event = from_http(headers, data) if "pipelineRun" in cloud_event.data:...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,507
import base64 from datetime import datetime import os import json import shared from flask import Flask, request def process_gitlab_event(headers, msg): # Unique hash for the event signature = shared.create_unique_id(msg) source = "gitlab" if "Mock" in headers: source += "mock" types = {"pus...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,508
import base64 import os import json import shared from flask import Flask, request def process_github_event(headers, msg): event_type = headers["X-Github-Event"] signature = headers["X-Hub-Signature"] source = "github" if "Mock" in headers: source += "mock" types = {"push", "pull_request", "...
Receives messages from a push subscription from Pub/Sub. Parses the message, and inserts it into BigQuery.
2,509
import os import nox The provided code snippet includes necessary dependencies for implementing the `_collect_dirs` function. Write a Python function `def _collect_dirs( start_dir, suffix="_test.py", recurse_further=False, )` to solve the following problem: Recursively collects a list of dirs that contain ...
Recursively collects a list of dirs that contain a file matching the given suffix. This works by listing the contents of directories and finding directories that have `*_test.py` files.
2,510
import os import nox def _session_tests(session, folder): """Runs py.test for a particular directory.""" session.chdir(folder) if os.path.exists("requirements.txt"): session.install("-r", "requirements.txt") session.run( "pytest", *(session.posargs), # Pytest will return ...
Runs py.test for a folder using the specified version of Python.
2,511
import os import nox def _determine_local_import_names(start_dir): """Determines all import names that should be considered "local". This is used when running the linter to insure that import order is properly checked. """ file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] ...
null
2,512
import sys from argparse import ArgumentParser, FileType from inspect import signature import numpy as np import m2cgen parser = ArgumentParser( prog="m2cgen", description="Generate code in native language for provided model.") parser.add_argument( "infile", type=FileType("rb"), nargs="?", defau...
null
2,513
import sys from argparse import ArgumentParser, FileType from inspect import signature import numpy as np import m2cgen LANGUAGE_TO_EXPORTER = { "python": (m2cgen.export_to_python, ["indent", "function_name"]), "java": (m2cgen.export_to_java, ["indent", "class_name", "package_name", "function_name"]), "c": ...
null
2,514
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Java code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. package_name : string, optional Java package name. By default no package name is used. class_name : string, optional The name of the generated class. indent : int, optional...
2,515
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Python code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : stri...
2,516
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a C code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,517
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Go code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,518
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a JavaScript code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : ...
2,519
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Visual Basic (also can be treated as VBA with some small manual changes, see a note below) code representation of the given model. .. note:: The generated code representation can be easily used as VBA code. You simply need to remove the first (`Module Model`) and the last (`End Module`) lines, and manually ...
2,520
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a C# code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. namespace : string, optional The namespace for the generated code. class_name : string, optional The name of the generated class. indent : int, optional The size of indents i...
2,521
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a PowerShell code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : ...
2,522
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a R code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,523
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a PHP code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,524
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Dart code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,525
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Haskell code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. module_name : string, optional The name of the generated module. indent : int, optional The size of indents in the generated code. function_name : string, optional Name ...
2,526
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Ruby code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,527
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a F# code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,528
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates a Rust code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. indent : int, optional The size of indents in the generated code. function_name : string, optional Name of the function in the generated code. Returns ------- code : string
2,529
from m2cgen import interpreters from m2cgen.assemblers import get_assembler_cls def _export(model, interpreter): assembler_cls = get_assembler_cls(model) model_ast = assembler_cls(model).assemble() return interpreter.interpret(model_ast) The provided code snippet includes necessary dependencies for impleme...
Generates an Elixir code representation of the given model. Parameters ---------- model : object The model object that should be transpiled into code. module_name : string, optional The name of the generated module. indent : int, optional The size of indents in the generated code. function_name : string, optional Name ...
2,530
import math from m2cgen import ast from m2cgen.assemblers import utils def abs(expr): expr = ast.IdExpr(expr, to_reuse=True) return ast.IfExpr( utils.lt(expr, ast.NumVal(0.0)), utils.sub(ast.NumVal(0.0), expr), expr)
null
2,531
import math from m2cgen import ast from m2cgen.assemblers import utils def tanh(expr): expr = ast.IdExpr(expr, to_reuse=True) tanh_expr = utils.sub( ast.NumVal(1.0), utils.div( ast.NumVal(2.0), utils.add( ast.ExpExpr( utils.mul( ...
null
2,532
import math from m2cgen import ast from m2cgen.assemblers import utils def sqrt(expr): return ast.PowExpr( base_expr=expr, exp_expr=ast.NumVal(0.5))
null
2,533
import math from m2cgen import ast from m2cgen.assemblers import utils def exp(expr): return ast.PowExpr( base_expr=ast.NumVal(math.e), exp_expr=expr)
null
2,534
import math from m2cgen import ast from m2cgen.assemblers import utils def log1p(expr): # Use trick to compute log1p for small values more accurate # https://www.johndcook.com/blog/2012/07/25/trick-for-computing-log1x/ expr = ast.IdExpr(expr, to_reuse=True) expr1p = utils.add(ast.NumVal(1.0), expr, to_...
null
2,535
import math from m2cgen import ast from m2cgen.assemblers import utils def atan(expr): expr = ast.IdExpr(expr, to_reuse=True) expr_abs = ast.AbsExpr(expr, to_reuse=True) expr_reduced = ast.IdExpr( ast.IfExpr( utils.gt(expr_abs, ast.NumVal(2.4142135623730950488)), utils.div(...
null
2,536
import math from m2cgen import ast from m2cgen.assemblers import utils def sigmoid(expr, to_reuse=False): neg_expr = ast.BinNumExpr(ast.NumVal(0.0), expr, ast.BinNumOpType.SUB) exp_expr = ast.ExpExpr(neg_expr) return ast.BinNumExpr( ast.NumVal(1.0), ast.BinNumExpr(ast.NumVal(1.0), exp_expr,...
null
2,537
import math from m2cgen import ast from m2cgen.assemblers import utils def softmax(exprs): exp_exprs = [ast.ExpExpr(e, to_reuse=True) for e in exprs] exp_sum_expr = utils.apply_op_to_expressions(ast.BinNumOpType.ADD, *exp_exprs, to_reuse=True) return ast.VectorVal([ ast.BinNumExpr(e, exp_sum_expr, ...
null
2,538
import numpy as np from m2cgen import ast def to_1d_array(var): return np.ravel(np.asarray(var))
null
2,539
import numpy as np from m2cgen import ast def to_2d_array(var): shape = np.shape(var) if len(shape) == 2: x, y = shape else: x, y = 1, np.size(var) return np.reshape(np.asarray(var), (x, y))
null
2,540
import json import math import numpy as np from m2cgen import ast from m2cgen.assemblers import utils from m2cgen.assemblers.base import ModelAssembler from m2cgen.assemblers.linear import _linear_to_ast def _split_estimator_params_by_classes(values, n_classes, params_seq_len): # Splits are computed based on a com...
null
2,541
import math import numpy as np from m2cgen import ast from m2cgen.assemblers import utils from m2cgen.assemblers.base import ModelAssembler def _linear_to_ast(coef, intercept): feature_weight_mul_ops = [ utils.mul(ast.FeatureRef(index), ast.NumVal(value)) for index, value in enumerate(coef) ] ...
null
2,542
from enum import Enum from inspect import getmembers, isclass from sys import modules import numpy as np class FeatureRef(Expr): def __init__(self, index): self.index = index def __str__(self): return f"FeatureRef({self.index})" def __eq__(self, other): return type(other) is FeatureR...
null
2,543
from enum import Enum from inspect import getmembers, isclass from sys import modules import numpy as np def _eq_bin_exprs(expr_one, expr_two, expected_type): return (type(expr_one) is expected_type and type(expr_two) is expected_type and expr_one.left == expr_two.left and expr_...
null
2,544
import math import re from collections import namedtuple from functools import lru_cache import numpy as np from m2cgen.ast import TOTAL_NUMBER_OF_EXPRESSIONS def get_file_content(path): return path.read_text(encoding="utf-8")
null
2,545
import math import re from collections import namedtuple from functools import lru_cache import numpy as np from m2cgen.ast import TOTAL_NUMBER_OF_EXPRESSIONS def _normalize_expr_name(name): return re.sub("(?!^)([A-Z]+)", r"_\1", name).lower() def _get_handler_name(expr_tpe): return f"interpret_{_normalize_exp...
null
2,546
import math import re from collections import namedtuple from functools import lru_cache import numpy as np from m2cgen.ast import TOTAL_NUMBER_OF_EXPRESSIONS def format_float(value): return np.format_float_positional(value, unique=True, trim="0")
null
2,547
def add_vectors(v1, v2): return [sum(i) for i in zip(v1, v2)]
null
2,548
def mul_vector_number(v1, num): return [i * num for i in v1]
null
2,549
def softmax(x): m = max(x) exps = [math.exp(i - m) for i in x] s = sum(exps) for idx, _ in enumerate(exps): exps[idx] /= s return exps
null
2,550
def sigmoid(x): if x < 0.0: z = math.exp(x) return z / (1.0 + z) return 1.0 / (1.0 + math.exp(-x))
null
2,551
def score(input): if input[2] <= 2.449999988079071: var0 = [1.0, 0.0, 0.0] else: if input[3] <= 1.75: if input[2] <= 4.950000047683716: if input[3] <= 1.6500000357627869: var0 = [0.0, 1.0, 0.0] else: var0 = [0....
null
2,552
def add_vectors(v1, v2): return [sum(i) for i in zip(v1, v2)] def mul_vector_number(v1, num): return [i * num for i in v1] def score(input): if input[3] <= 0.75: var0 = [1.0, 0.0, 0.0] else: if input[2] <= 4.75: var0 = [0.0, 1.0, 0.0] else: if input[2] <=...
null
2,553
import math def score(input): var0 = math.exp(-0.06389634699048878 * (math.pow(5.1 - input[0], 2.0) + math.pow(2.5 - input[1], 2.0) + math.pow(3.0 - input[2], 2.0) + math.pow(1.1 - input[3], 2.0))) var1 = math.exp(-0.06389634699048878 * (math.pow(4.9 - input[0], 2.0) + math.pow(2.4 - input[1], 2.0) + math.pow(...
null
2,554
import math def softmax(x): m = max(x) exps = [math.exp(i - m) for i in x] s = sum(exps) for idx, _ in enumerate(exps): exps[idx] /= s return exps def score(input): if input[2] >= 2.45: var0 = -0.21995015 else: var0 = 0.4302439 if input[2] >= 2.45: var1 =...
null
2,555
import math def softmax(x): m = max(x) exps = [math.exp(i - m) for i in x] s = sum(exps) for idx, _ in enumerate(exps): exps[idx] /= s return exps def score(input): if input[2] > 3.1500000000000004: var0 = -1.1986122886681099 else: if input[1] > 3.35: var...
null
2,556
def score(input): return [9.700311953536998 + input[0] * -0.4128360473754751 + input[1] * 0.9680426131053453 + input[2] * -2.498310603183548 + input[3] * -1.0723230787022542, 2.1575759475871163 + input[0] * 0.5400806228605453 + input[1] * -0.3245383349519669 + input[2] * -0.2034493200950831 + input[3] * -0.933818...
null
2,557
def score(input): if input[12] <= 9.724999904632568: if input[5] <= 7.437000036239624: if input[7] <= 1.4849499464035034: var0 = 50.0 else: var0 = 26.681034482758605 else: var0 = 44.96896551724139 else: if input[12] <=...
null
2,558
def score(input): if input[12] <= 9.845000267028809: if input[5] <= 6.959500074386597: if input[6] <= 96.20000076293945: var0 = 25.093162393162395 else: var0 = 50.0 else: var0 = 38.074999999999996 else: if input[12] <=...
null
2,559
import math def score(input): return 25.346480984077544 + math.exp(-0.0000036459736698188483 * (math.pow(16.8118 - input[0], 2.0) + math.pow(0.0 - input[1], 2.0) + math.pow(18.1 - input[2], 2.0) + math.pow(0.0 - input[3], 2.0) + math.pow(0.7 - input[4], 2.0) + math.pow(5.277 - input[5], 2.0) + math.pow(98.1 - inpu...
null