Datasets:

function_name
stringlengths
1
63
docstring
stringlengths
50
5.89k
masked_code
stringlengths
50
882k
implementation
stringlengths
169
12.9k
start_line
int32
1
14.6k
end_line
int32
16
14.6k
file_content
stringlengths
274
882k
read_go_deps
read_go_deps returns a list of module dependencies in JSON format. Main modules are excluded; only dependencies are returned. Unlike `go list -m all`, this function excludes modules that are only required for running tests.
from __future__ import print_function import glob import os import datetime import argparse import json import csv import re import pdb import copy import subprocess import fnmatch import textwrap import sys import tempfile DEFAULT_BUILD_TAGS = "darwin,linux,windows" # Get the beats repo root directory, making sure ...
def read_go_deps(main_packages, build_tags): """ read_go_deps returns a list of module dependencies in JSON format. Main modules are excluded; only dependencies are returned. Unlike `go list -m all`, this function excludes modules that are only required for running tests. """ go_list_args =...
40
65
from __future__ import print_function import glob import os import datetime import argparse import json import csv import re import pdb import copy import subprocess import fnmatch import textwrap import sys import tempfile DEFAULT_BUILD_TAGS = "darwin,linux,windows" # Get the beats repo root directory, making sure ...
__init__
Initialize the DPOptimizerClass. Args: l2_norm_clip: Clipping norm (max L2 norm of per microbatch gradients) noise_multiplier: Ratio of the standard deviation to the clipping norm num_microbatches: The number of microbatches into which each minibatch is split.
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
def __init__( self, l2_norm_clip, noise_multiplier, changing_clipping=False, num_microbatches=None, gradient_norm=None, *args, # pylint: disable=keyword-arg-before-vararg, g-doc-args **kwargs): """Initialize the DPOptimizerClass. Args: ...
44
71
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
algebraic_connectivity
Return the algebraic connectivity of an undirected graph. The algebraic connectivity of a connected undirected graph is the second smallest eigenvalue of its Laplacian matrix. Parameters ---------- G : NetworkX graph An undirected graph. weight : object, optional (default: None) The data key used to determin...
# -*- coding: utf-8 -*- # Copyright (C) 2014 ysitu <ysitu@users.noreply.github.com> # All rights reserved. # BSD license. # # Author: ysitu <ysitu@users.noreply.github.com> """ Algebraic connectivity and Fiedler vectors of undirected graphs. """ from functools import partial import networkx as nx from networkx.utils im...
@not_implemented_for('directed') def algebraic_connectivity(G, weight='weight', normalized=False, tol=1e-8, method='tracemin_pcg'): """Return the algebraic connectivity of an undirected graph. The algebraic connectivity of a connected undirected graph is the second smallest eigen...
330
407
# -*- coding: utf-8 -*- # Copyright (C) 2014 ysitu <ysitu@users.noreply.github.com> # All rights reserved. # BSD license. # # Author: ysitu <ysitu@users.noreply.github.com> """ Algebraic connectivity and Fiedler vectors of undirected graphs. """ from functools import partial import networkx as nx from networkx.utils im...
fiedler_vector
Return the Fiedler vector of a connected undirected graph. The Fiedler vector of a connected undirected graph is the eigenvector corresponding to the second smallest eigenvalue of the Laplacian matrix of of the graph. Parameters ---------- G : NetworkX graph An undirected graph. weight : object, optional (defaul...
# -*- coding: utf-8 -*- # Copyright (C) 2014 ysitu <ysitu@users.noreply.github.com> # All rights reserved. # BSD license. # # Author: ysitu <ysitu@users.noreply.github.com> """ Algebraic connectivity and Fiedler vectors of undirected graphs. """ from functools import partial import networkx as nx from networkx.utils im...
@not_implemented_for('directed') def fiedler_vector(G, weight='weight', normalized=False, tol=1e-8, method='tracemin_pcg'): """Return the Fiedler vector of a connected undirected graph. The Fiedler vector of a connected undirected graph is the eigenvector corresponding to the second smal...
410
488
# -*- coding: utf-8 -*- # Copyright (C) 2014 ysitu <ysitu@users.noreply.github.com> # All rights reserved. # BSD license. # # Author: ysitu <ysitu@users.noreply.github.com> """ Algebraic connectivity and Fiedler vectors of undirected graphs. """ from functools import partial import networkx as nx from networkx.utils im...
base_setup
A setup phase for the test Args: interface_type: Interface type storageclass_factory: A fixture to create everything needed for a storage class
""" Test to verify performance of attaching number of pods as a bulk, each pod attached to one pvc only The test results will be uploaded to the ES server """ import logging import os import pytest import pathlib import time from concurrent.futures import ThreadPoolExecutor from ocs_ci.framework.testlib import perform...
@pytest.fixture() def base_setup(self, project_factory, interface_type, storageclass_factory): """ A setup phase for the test Args: interface_type: Interface type storageclass_factory: A fixture to create everything needed for a storage class """ ...
45
63
""" Test to verify performance of attaching number of pods as a bulk, each pod attached to one pvc only The test results will be uploaded to the ES server """ import logging import os import pytest import pathlib import time from concurrent.futures import ThreadPoolExecutor from ocs_ci.framework.testlib import perform...
init_full_results
Initialize the full results object which will send to the ES server Args: full_results (obj): an empty ResultsAnalyse object Returns: ResultsAnalyse (obj): the input object filled with data
""" Test to verify performance of attaching number of pods as a bulk, each pod attached to one pvc only The test results will be uploaded to the ES server """ import logging import os import pytest import pathlib import time from concurrent.futures import ThreadPoolExecutor from ocs_ci.framework.testlib import perform...
def init_full_results(self, full_results): """ Initialize the full results object which will send to the ES server Args: full_results (obj): an empty ResultsAnalyse object Returns: ResultsAnalyse (obj): the input object filled with data """ ...
226
240
""" Test to verify performance of attaching number of pods as a bulk, each pod attached to one pvc only The test results will be uploaded to the ES server """ import logging import os import pytest import pathlib import time from concurrent.futures import ThreadPoolExecutor from ocs_ci.framework.testlib import perform...
add_active_repository
Adds a new active repository identified by 'repository_id' and that uses 'plan' as base. Args: repository_id (str): The ID to give to the repository. This must be unique, if it is not an error will be returned. plan (str): The name of the plan to use as base for the repository. If it does not exist the...
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
def add_active_repository(self, repository_id: str, plan: str, archive: str, **kwargs): """Adds a new active repository identified by 'repository_id' and that uses 'plan' as base. Args: repository_id (str): The ID to give to the repository. This must be unique, if it is not an error wil...
5,063
5,108
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
check_cloud_params
Checks that inside kwargs there is a valid set of parameters to add a cloud repository Args: archive (str): The archive to use for the repository.
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
@staticmethod def check_cloud_params(archive: str, **kwargs) -> Optional[List[str]]: """Checks that inside kwargs there is a valid set of parameters to add a cloud repository Args: archive (str): The archive to use for the repository. """ # If not an s3 archive skip t...
5,110
5,134
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
archive_repository
Archive an repository. The archived repository will have the id `new_id` Args: repository_id (str): The active repository ID to be archived new_id (str): The id that will be given to the archived repository
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
def archive_repository(self, repository_id, new_id): """Archive an repository. The archived repository will have the id `new_id` Args: repository_id (str): The active repository ID to be archived new_id (str): The id that will be given to the archived repository """ ...
5,136
5,150
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
list_repositories
List the backup repositories. If a repository state is given only repositories in that state will be listed. This command supports listing both in json and human friendly format. Args: state (str, optional): One of ['active', 'imported', 'archived']. The repository on this state will be retrieved. jso...
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
def list_repositories(self, state=None, json_out=False): """List the backup repositories. If a repository state is given only repositories in that state will be listed. This command supports listing both in json and human friendly format. Args: state (str, optional): On...
5,152
5,173
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
human_firendly_print_repository
Print the repository in a human friendly format Args: repository (obj): The backup repository information
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
@staticmethod def human_firendly_print_repository(repository): """Print the repository in a human friendly format Args: repository (obj): The backup repository information """ print(f'ID: {repository["id"]}') print(f'State: {repository["state"]}') pr...
5,197
5,224
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
human_friendly_print_running_tasks
Prints the running task summary in a human friendly way Args: one_off (map<str, task object>): Running one off tasks scheduled (map<str, task object>): Running scheduled tasks
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
@staticmethod def human_friendly_print_running_tasks(one_off, scheduled): """Prints the running task summary in a human friendly way Args: one_off (map<str, task object>): Running one off tasks scheduled (map<str, task object>): Running scheduled tasks """ ...
5,226
5,254
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
human_friendly_print_repositories
This will print the repositories in a tabular format Args: repository_map (map<state (str), repository (list of objects)>)
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
@staticmethod def human_friendly_print_repositories(repositories_map): """This will print the repositories in a tabular format Args: repository_map (map<state (str), repository (list of objects)>) """ repository_count = 0 id_pad = 5 plan_pad = 7 ...
5,273
5,314
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
add_plan
Add a new backup plan The validation of the inputs in the CLI is intentionally lacking as this is offloaded to the backup service. Args: name (str): The name to give the new plan. It must be unique. services (optional list): A list of services to backup if empty all services are backed up. tasks (optional ...
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
def add_plan(self, name: str, services: Optional[str], tasks: Optional[List[str]], description: Optional[str]): """Add a new backup plan The validation of the inputs in the CLI is intentionally lacking as this is offloaded to the backup service. Args: name (str): The name to giv...
5,367
5,403
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
get_plan
Gets a backup plan by name Args: name (str): The name of the plan to retrieve json_output (bool): Whether to print in JSON or a more human friendly way
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
def get_plan(self, name: str, json_output: bool = False): """Gets a backup plan by name Args: name (str): The name of the plan to retrieve json_output (bool): Whether to print in JSON or a more human friendly way """ if not name: _exit_if_errors([...
5,414
5,429
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
list_plans
Prints all the plans stored in the backup service Args: json_output (bool): Whether to print in JSON or a more human friendly way
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
def list_plans(self, json_output: bool = False): """Prints all the plans stored in the backup service Args: json_output (bool): Whether to print in JSON or a more human friendly way """ plans, errors = self.rest.list_backup_plans() _exit_if_errors(errors) ...
5,431
5,442
"""A Couchbase CLI subcommand""" import getpass import inspect import ipaddress import json import os import platform import random import re import string import subprocess import sys import urllib.parse import tempfile import time from typing import Optional, List, Any, Dict from argparse import ArgumentError, Arg...
__init__
Input properties used for looking up and filtering GroupMemberships resources. :param pulumi.Input[str] group_id: ID of a Okta group. :param pulumi.Input[Sequence[pulumi.Input[str]]] users: The list of Okta user IDs which the group should have membership managed for.
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
def __init__(__self__, *, group_id: Optional[pulumi.Input[str]] = None, users: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ Input properties used for looking up and filtering GroupMemberships resources. :param pulumi.Input[str] group_id: ...
53
64
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
get
Get an existing GroupMemberships resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Op...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, group_id: Optional[pulumi.Input[str]] = None, users: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None) -> 'GroupMemberships': """ ...
195
217
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
gen_attributes
Generate list of attributes for the API request. Example of input list: ['tag_name:tag_value1', 'tag_value2'] Output of the function for the given input list: [{'key': 'tag_name', 'value': 'tag_value1'}, {'value': 'tag_value2'}] :param rp_attributes: List of attributes(tags) :return: Correctly created li...
"""This module contains common functions-helpers of the client and agents. Copyright (c) 2018 http://reportportal.io . 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/...
def gen_attributes(rp_attributes): """Generate list of attributes for the API request. Example of input list: ['tag_name:tag_value1', 'tag_value2'] Output of the function for the given input list: [{'key': 'tag_name', 'value': 'tag_value1'}, {'value': 'tag_value2'}] :param rp_attributes: List ...
22
48
"""This module contains common functions-helpers of the client and agents. Copyright (c) 2018 http://reportportal.io . 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/...
neighbord_analysis
Given an array xas this function compute the distance between the elements the mean distance and the variance Author: Michele Monti Args: x_as: the name of the list or data set that you want: Kwargs: column: is the column of the data set that you need to analyze Returns: mean_distanc...
# MASKED: neighbord_analysis function (lines 1-28)
def neighbord_analysis(x_as, column = 0): """ Given an array xas this function compute the distance between the elements the mean distance and the variance Author: Michele Monti Args: x_as: the name of the list or data set that you want: Kwargs: column: is the column of the data set that you need to ana...
1
28
def neighbord_analysis(x_as, column = 0): """ Given an array xas this function compute the distance between the elements the mean distance and the variance Author: Michele Monti Args: x_as: the name of the list or data set that you want: Kwargs: column: is the column of the data set that you need to ana...
start_training
Executes a training function on all workers in a separate thread. ``finish_training`` should be called after this. Args: train_func (Callable): The training function to run on each worker.
import logging from typing import Callable, TypeVar, List, Optional, Dict import ray from ray.exceptions import RayActorError from ray.util.sgd.v2.worker_group import WorkerGroup from ray.util.sgd.v2.session import init_session, get_session, shutdown_session T = TypeVar("T") logger = logging.getLogger(__name__) cl...
def start_training(self, train_func: Callable[[], T]) -> None: """Executes a training function on all workers in a separate thread. ``finish_training`` should be called after this. Args: train_func (Callable): The training function to run on each worker. """ # ...
63
99
import logging from typing import Callable, TypeVar, List, Optional, Dict import ray from ray.exceptions import RayActorError from ray.util.sgd.v2.worker_group import WorkerGroup from ray.util.sgd.v2.session import init_session, get_session, shutdown_session T = TypeVar("T") logger = logging.getLogger(__name__) cl...
__init__
Creates a _TreeEnsembleSavable object. Args: resource_handle: handle to the decision tree ensemble variable. create_op: the op to initialize the variable. name: the name to save the tree ensemble variable under.
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
def __init__(self, resource_handle, create_op, name): """Creates a _TreeEnsembleSavable object. Args: resource_handle: handle to the decision tree ensemble variable. create_op: the op to initialize the variable. name: the name to save the tree ensemble variable under. """ stamp_toke...
169
191
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
promote_ase_atoms
Convert ASE Atoms object to the one usable by SPRKKR. For the case of the usability it is a bit ugly hack: The __class__ attribute is replaced so the extra methods and properties of the objects will be available. Parameters ---------- obj: ase.Atoms The atoms object to be promoted to be used for SPRKKR calculations ...
""" This file contains SPRKKRAtoms - an enhanced version of Atoms to be used with SPRKKR """ from ase import Atoms from ..common.unique_values import UniqueValuesMapping import spglib from ase.spacegroup import Spacegroup import numpy as np from ..sprkkr.sites import Site from ..common.misc import numpy_index class ...
@staticmethod def promote_ase_atoms(obj, symmetry=None): """ Convert ASE Atoms object to the one usable by SPRKKR. For the case of the usability it is a bit ugly hack: The __class__ attribute is replaced so the extra methods and properties of the objects will be available. ...
16
49
""" This file contains SPRKKRAtoms - an enhanced version of Atoms to be used with SPRKKR """ from ase import Atoms from ..common.unique_values import UniqueValuesMapping import spglib from ase.spacegroup import Spacegroup import numpy as np from ..sprkkr.sites import Site from ..common.misc import numpy_index class ...
_type_repr
Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall back on repr(obj).
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
def _type_repr(obj): """Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall b...
44
63
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
__init__
Instantiate an instance of ``Node``. Note: most often, you want to use the Graph APIs, i.e. ``Graph.call_module``, ``Graph.call_method``, etc. rather than instantiating a ``Node`` directly. Args: graph (Graph): The ``Graph`` to which this ``Node`` should belong. name (str): The name to which the output of thi...
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
@compatibility(is_backward_compatible=True) def __init__(self, graph: 'Graph', name: str, op: str, target: 'Target', args: Tuple['Argument', ...], kwargs: Dict[str, 'Argument'], return_type : Optional[Any] = None) -> None: """ Instantiate an instance of ``Node``...
120
198
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
_pretty_print_target
Make target printouts more user-friendly. 1) builtins will be printed as `builtins.xyz` 2) operators will be printed as `operator.xyz` 3) other callables will be printed with qualfied name, e.g. torch.add
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
def _pretty_print_target(self, target): """ Make target printouts more user-friendly. 1) builtins will be printed as `builtins.xyz` 2) operators will be printed as `operator.xyz` 3) other callables will be printed with qualfied name, e.g. torch.add """ if isin...
382
402
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
replace_all_uses_with
Replace all uses of ``self`` in the Graph with the Node ``replace_with``. Args: replace_with (Node): The node to replace all uses of ``self`` with. Returns: The list of Nodes on which this change was made.
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
@compatibility(is_backward_compatible=True) def replace_all_uses_with(self, replace_with : 'Node') -> List['Node']: """ Replace all uses of ``self`` in the Graph with the Node ``replace_with``. Args: replace_with (Node): The node to replace all uses of ``self`` with. ...
460
488
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
is_impure
Returns whether this op is impure, i.e. if its op is a placeholder or output, or if a call_function or call_module which is impure. Returns: bool: If the op is impure or not.
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
@compatibility(is_backward_compatible=False) def is_impure(self): """ Returns whether this op is impure, i.e. if its op is a placeholder or output, or if a call_function or call_module which is impure. Returns: bool: If the op is impure or not. """ i...
490
518
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
normalized_arguments
Returns normalized arguments to Python targets. This means that `args/kwargs` will be matched up to the module/functional's signature and return exclusively kwargs in positional order if `normalize_to_only_use_kwargs` is true. Also populates default values. Does not support positional-only parameters or varargs paramet...
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
@compatibility(is_backward_compatible=False) def normalized_arguments( self, root : torch.nn.Module, arg_types : Optional[Tuple[Any]] = None, kwarg_types : Optional[Dict[str, Any]] = None, normalize_to_only_use_kwargs : bool = False) -> Optional[ArgsKwargsPair]: """ ...
520
554
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
replace_input_with
Loop through input nodes of ``self``, and replace all instances of ``old_input`` with ``new_input``. Args: old_input (Node): The old input node to be replaced. new_input (Node): The new input node to replace ``old_input``.
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from torch.f...
@compatibility(is_backward_compatible=True) def replace_input_with(self, old_input: 'Node', new_input: 'Node'): """ Loop through input nodes of ``self``, and replace all instances of ``old_input`` with ``new_input``. Args: old_input (Node): The old input node to be ...
556
574
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types from ...
combineCommandLineOptionsDictIntoShellCommand
Write out the compas input parameters into a shell string. Ensure the Compas executable is first, and not repeated. Options are non-ordered.
import numpy as np import sys import os import re import ntpath from subprocess import call #### DISCLAIMER: This script uses the `pythonSubmit.py` format #### that has been replaced by the `runSubmit.py` and #### `compasConfigDefault.yaml` combo as of v02.25.10. #### The `pythonSubmit.py` format will eventually beco...
def combineCommandLineOptionsDictIntoShellCommand(commandOptions): """ Write out the compas input parameters into a shell string. Ensure the Compas executable is first, and not repeated. Options are non-ordered. """ shellCommand = commandOptions['compas_executable'] del commandOptions['comp...
771
783
import numpy as np import sys import os import re import ntpath from subprocess import call #### DISCLAIMER: This script uses the `pythonSubmit.py` format #### that has been replaced by the `runSubmit.py` and #### `compasConfigDefault.yaml` combo as of v02.25.10. #### The `pythonSubmit.py` format will eventually beco...
thresholded_value_comparison
Compare -2,-1,0,1,2 gene-level thresholded calls. metric can be either hamming (number of discrepancies in each gene) or manhattan (sum of 'distances' between each gene so a 1 to -1 change is 2). Returns a vector of each gene's metric.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 22 17:28:54 2018 @author: galengao This is the original analysis code as it exists in the environment where it was writen and initially run. Portions and modifications of this script constitute all other .py scripts in this directory. """ import nu...
def thresholded_value_comparison(df_hg38, df_hg19, metric='hamming'): """Compare -2,-1,0,1,2 gene-level thresholded calls. metric can be either hamming (number of discrepancies in each gene) or manhattan (sum of 'distances' between each gene so a 1 to -1 change is 2). Returns a vector of each gene's me...
106
117
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 22 17:28:54 2018 @author: galengao This is the original analysis code as it exists in the environment where it was writen and initially run. Portions and modifications of this script constitute all other .py scripts in this directory. """ import nu...
_DashboardJsonToRawRows
Formats a Dashboard JSON dict as a list of row dicts. For the dashboard to begin accepting the Telemetry Dashboard JSON format as per go/telemetry-json, this function chunks a Dashboard JSON literal into rows and passes the resulting list to _AddTasks. Args: dash_json_dict: A dashboard JSON v1.0 dict. Returns: A...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
def _DashboardJsonToRawRows(dash_json_dict): """Formats a Dashboard JSON dict as a list of row dicts. For the dashboard to begin accepting the Telemetry Dashboard JSON format as per go/telemetry-json, this function chunks a Dashboard JSON literal into rows and passes the resulting list to _AddTasks. Args: ...
161
231
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
_AddTasks
Puts tasks on queue for adding data. Args: data: A list of dictionaries, each of which represents one point.
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
def _AddTasks(data): """Puts tasks on queue for adding data. Args: data: A list of dictionaries, each of which represents one point. """ task_list = [] for data_sublist in _Chunk(data, _TASK_QUEUE_SIZE): task_list.append(taskqueue.Task( url='/add_point_queue', params={'data': json.dum...
249
264
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
_ValidateRowDict
Checks all fields in the input dictionary. Args: row: A dictionary which represents one point. test_map: A dictionary mapping test paths to last added revision. Raises: BadRequestError: The input was not valid.
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
def _ValidateRowDict(row, test_map): """Checks all fields in the input dictionary. Args: row: A dictionary which represents one point. test_map: A dictionary mapping test paths to last added revision. Raises: BadRequestError: The input was not valid. """ required_fields = ['master', 'bot', 'test...
552
568
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
_ValidateRowId
Checks whether the ID for a Row is OK. Args: row_dict: A dictionary with new point properties, including "revision". test_map: A dictionary mapping test paths to the last previously added revision for each test. Raises: BadRequestError: The revision is not acceptable for some reason.
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
def _ValidateRowId(row_dict, test_map): """Checks whether the ID for a Row is OK. Args: row_dict: A dictionary with new point properties, including "revision". test_map: A dictionary mapping test paths to the last previously added revision for each test. Raises: BadRequestError: The revision...
612
640
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
_GetSupplementalColumns
Gets a dict of supplemental columns. If any columns are invalid, a warning is logged and they just aren't included, but no exception is raised. Individual rows may specify up to _MAX_NUM_COLUMNS extra data, revision, and annotation columns. These columns must follow formatting rules for their type. Invalid columns ar...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
def _GetSupplementalColumns(row): """Gets a dict of supplemental columns. If any columns are invalid, a warning is logged and they just aren't included, but no exception is raised. Individual rows may specify up to _MAX_NUM_COLUMNS extra data, revision, and annotation columns. These columns must follow form...
753
780
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """URL endpoint to allow Buildbot slaves to post data to the dashboard.""" import copy import json import logging import math import re from google.appengi...
convert_k8s_obj_to_json
Builds a JSON K8s object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the prop...
# Copyright 2018 Google LLC # # 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 or agreed to in writing, ...
@staticmethod def convert_k8s_obj_to_json(k8s_obj): """ Builds a JSON K8s object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each elemen...
132
183
# Copyright 2018 Google LLC # # 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 or agreed to in writing, ...
__init__
Initialize an Offline Connection object. >>> monascastatsd = MonascaStatsd() :name: the name for this client. Everything sent by this client will be prefixed by name :param host: the host of the MonascaStatsd server. :param port: the port of the MonascaStatsd server. :param max_buffer_size: Maximum number of met...
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP # Copyright 2016 FUJITSU LIMITED # 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 #...
def __init__(self, host='localhost', port=8125, max_buffer_size=50): """Initialize an Offline Connection object. >>> monascastatsd = MonascaStatsd() :name: the name for this client. Everything sent by this client will be prefixed by name :param host: the host of the Mo...
111
126
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP # Copyright 2016 FUJITSU LIMITED # 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 #...
value_iteration
Solves the shortest path problem using value iteration :input town_map env : The town_map environment in which we seek to find the shortest path. :input float gamma : The discount factor. :input float epsilon : accuracy of the value iteration procedure. :return numpy.ar...
import numpy as np import matplotlib.pyplot as plt import time from IPython import display # Implemented methods methods = ['DynProg', 'ValIter']; # Some colours LIGHT_RED = '#FFC4CC'; LIGHT_GREEN = '#95FD99'; BLACK = '#000000'; WHITE = '#FFFFFF'; LIGHT_PURPLE = '#E8D0FF'; LIGHT_ORANGE = '#FAE0C3'; ...
def value_iteration(env, gamma, epsilon): """ Solves the shortest path problem using value iteration :input town_map env : The town_map environment in which we seek to find the shortest path. :input float gamma : The discount factor. :inpu...
221
275
import numpy as np import matplotlib.pyplot as plt import time from IPython import display # Implemented methods methods = ['DynProg', 'ValIter']; # Some colours LIGHT_RED = '#FFC4CC'; LIGHT_GREEN = '#95FD99'; BLACK = '#000000'; WHITE = '#FFFFFF'; LIGHT_PURPLE = '#E8D0FF'; LIGHT_ORANGE = '#FAE0C3'; ...
__move
Makes a step in the town_map, given a current position and an action. If the action STAY or an inadmissible action is used, the robber stays in place. :return integer next_cell corresponding to position (x,y) x (x,y) on the town_map that agent transitions to.
import numpy as np import matplotlib.pyplot as plt import time from IPython import display # Implemented methods methods = ['DynProg', 'ValIter']; # Some colours LIGHT_RED = '#FFC4CC'; LIGHT_GREEN = '#95FD99'; BLACK = '#000000'; WHITE = '#FFFFFF'; LIGHT_PURPLE = '#E8D0FF'; LIGHT_ORANGE = '#FAE0C3'; ...
def __move(self, state, action): """ Makes a step in the town_map, given a current position and an action. If the action STAY or an inadmissible action is used, the robber stays in place. :return integer next_cell corresponding to position (x,y) x (x,y) on the town_map that agent tr...
80
104
import numpy as np import matplotlib.pyplot as plt import time from IPython import display # Implemented methods methods = ['DynProg', 'ValIter']; # Some colours LIGHT_RED = '#FFC4CC'; LIGHT_GREEN = '#95FD99'; BLACK = '#000000'; WHITE = '#FFFFFF'; LIGHT_PURPLE = '#E8D0FF'; LIGHT_ORANGE = '#FAE0C3'; ...
__transitions
Computes the transition probabilities for every state action pair. :return numpy.tensor transition probabilities: tensor of transition probabilities of dimension S*S*A
import numpy as np import matplotlib.pyplot as plt import time from IPython import display # Implemented methods methods = ['DynProg', 'ValIter']; # Some colours LIGHT_RED = '#FFC4CC'; LIGHT_GREEN = '#95FD99'; BLACK = '#000000'; WHITE = '#FFFFFF'; LIGHT_PURPLE = '#E8D0FF'; LIGHT_ORANGE = '#FAE0C3'; ...
def __transitions(self): """ Computes the transition probabilities for every state action pair. :return numpy.tensor transition probabilities: tensor of transition probabilities of dimension S*S*A """ # Initialize the transition probailities tensor (S,S,A) dim...
120
145
import numpy as np import matplotlib.pyplot as plt import time from IPython import display # Implemented methods methods = ['DynProg', 'ValIter']; # Some colours LIGHT_RED = '#FFC4CC'; LIGHT_GREEN = '#95FD99'; BLACK = '#000000'; WHITE = '#FFFFFF'; LIGHT_PURPLE = '#E8D0FF'; LIGHT_ORANGE = '#FAE0C3'; ...
_verify_local_backends
Return the local backends in `SDK_STANDARD_BACKENDS` that are effectively available (as some of them might depend on the presence of an optional dependency or on the existence of a binary). Returns: dict[str:BaseBackend]: a dict of the local backends instances for the backends that could be instantiated, k...
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name, bad-continuation """Provider for local backends.""" import logging from qiskit._qiskiterror...
@classmethod def _verify_local_backends(cls): """ Return the local backends in `SDK_STANDARD_BACKENDS` that are effectively available (as some of them might depend on the presence of an optional dependency or on the existence of a binary). Returns: dict[str:B...
73
94
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name, bad-continuation """Provider for local backends.""" import logging from qiskit._qiskiterror...
draw_collection
Draw a collection of lines. Parameters ---------- collection: list of compas.geometry.Line A collection of ``Line`` objects. names : list of str, optional Individual names for the lines. colors : color or list of color, optional A color specification for the lines as a single color or a list of individual ...
from __future__ import print_function from __future__ import absolute_import from __future__ import division try: basestring except NameError: basestring = str import compas_rhino from compas.utilities import iterable_like from compas_rhino.artists._primitiveartist import PrimitiveArtist __all__ = ['LineArt...
@staticmethod def draw_collection(collection, names=None, colors=None, layer=None, clear=False, add_to_group=False, group_name=None): """Draw a collection of lines. Parameters ---------- collection: list of compas.geometry.Line A collection of ``Line`` objects. ...
48
98
from __future__ import print_function from __future__ import absolute_import from __future__ import division try: basestring except NameError: basestring = str import compas_rhino from compas.utilities import iterable_like from compas_rhino.artists._primitiveartist import PrimitiveArtist __all__ = ['LineArt...
get_cython_func_and_vals
Find the appropriate cython function, casting if necessary. Parameters ---------- values : np.ndarray is_numeric : bool Returns ------- func : callable values : np.ndarray
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
def get_cython_func_and_vals(self, values: np.ndarray, is_numeric: bool): """ Find the appropriate cython function, casting if necessary. Parameters ---------- values : np.ndarray is_numeric : bool Returns ------- func : callable valu...
172
208
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
_get_result_dtype
Get the desired dtype of a result based on the input dtype and how it was computed. Parameters ---------- dtype : np.dtype or ExtensionDtype Input dtype. Returns ------- np.dtype or ExtensionDtype The desired dtype of the result.
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
def _get_result_dtype(self, dtype: DtypeObj) -> DtypeObj: """ Get the desired dtype of a result based on the input dtype and how it was computed. Parameters ---------- dtype : np.dtype or ExtensionDtype Input dtype. Returns ------- ...
285
314
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
agg_series
Parameters ---------- obj : Series func : function taking a Series and returning a scalar-like preserve_dtype : bool Whether the aggregation is known to be dtype-preserving. Returns ------- np.ndarray or ExtensionArray
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
@final def agg_series( self, obj: Series, func: Callable, preserve_dtype: bool = False ) -> ArrayLike: """ Parameters ---------- obj : Series func : function taking a Series and returning a scalar-like preserve_dtype : bool Whether the aggr...
947
987
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
scalar_mul
Multiplies a scalar times a `Tensor` or `IndexedSlices` object. Intended for use in gradient code which might deal with `IndexedSlices` objects, which are easy to multiply by a scalar but more expensive to multiply with arbitrary tensors. Args: scalar: A 0-D scalar `Tensor`. Must have known shape. x: A `Tensor` o...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.scalar_mul", "scalar_mul"]) def scalar_mul(scalar, x, name=None): """Multiplies a scalar times a `Tensor` or `IndexedSlices` object. Intended for use in gradient code which might deal with `IndexedSlices` objects, which are easy to multiply by a scalar but more expensive to multiply with a...
314
343
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
round
Rounds the values of a tensor to the nearest integer, element-wise. Rounds half to even. Also known as bankers rounding. If you want to round according to the current system rounding mode use tf::cint. For example: ```python x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5]) tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ] ``` ...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export("math.round", "round") @dispatch.add_dispatch_support def round(x, name=None): # pylint: disable=redefined-builtin """Rounds the values of a tensor to the nearest integer, element-wise. Rounds half to even. Also known as bankers rounding. If you want to round according to the current system rounding...
531
556
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
_OverrideBinaryOperatorHelper
Register operators with different tensor and scalar versions. If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices, sp_values, sp_shape, dense)` and outputs `(new_sp_values)`. Args: func: the operator op_name: name of the operator being overridden clazz_object: class to override for. Either `...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor): """Register operators with different tensor and scalar versions. If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices, sp_values, sp_shape, dense)` and outputs `(new_sp_values)`. Args: func: the operator op_na...
798
861
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_sum_v1
Computes the sum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dimensio...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_sum", "reduce_sum"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_sum_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, ...
1,236
1,288
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
count_nonzero
Computes number of nonzero elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.count_nonzero", "count_nonzero"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") @deprecation.deprecated_args( None, "reduction_indices is deprecated, use axis instead", "axis") def count_nonzero(input_tensor, axis=None, ...
1,339
1,407
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
count_nonzero_v2
Computes number of nonzero elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, all d...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export("math.count_nonzero", v1=[]) def count_nonzero_v2(input, # pylint: disable=redefined-builtin axis=None, keepdims=None, dtype=dtypes.int64, name=None): """Computes number of nonzero elements across dimensions of a tensor. ...
1,410
1,475
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_prod_v1
Computes the product of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dime...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_prod", "reduce_prod"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_prod_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=Non...
1,729
1,769
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_min_v1
Computes the minimum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dime...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_min", "reduce_min"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_min_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, ...
1,772
1,812
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_max_v1
Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dime...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_max", "reduce_max"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_max_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, ...
1,851
1,891
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_all_v1
Computes the "logical and" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, al...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_all", "reduce_all"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_all_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, ...
1,930
1,979
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_any_v1
Computes the "logical or" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_any", "reduce_any"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_any_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, ...
2,027
2,076
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_logsumexp_v1
Computes log(sum(exp(elements across dimensions of a tensor))). Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, a...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export(v1=["math.reduce_logsumexp", "reduce_logsumexp"]) @deprecation.deprecated_args( None, "keep_dims is deprecated, use keepdims instead", "keep_dims") def reduce_logsumexp_v1(input_tensor, axis=None, keepdims=None, name=None, ...
2,124
2,175
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduce_logsumexp
Computes log(sum(exp(elements across dimensions of a tensor))). Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, a...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export("math.reduce_logsumexp", "reduce_logsumexp", v1=[]) def reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): """Computes log(sum(exp(elements across dimensions of a tensor))). Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tenso...
2,178
2,235
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
_as_indexed_slices
Convert 'x' to IndexedSlices. Convert a dense Tensor to a block-sparse IndexedSlices. Args: x: Either a Tensor object, or an IndexedSlices object. optimize: if true, attempt to optimize the conversion of 'x'. Returns: An IndexedSlices object. Raises: TypeError: If 'x' is not a Tensor or an IndexedSlices obj...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
def _as_indexed_slices(x, optimize=True): """Convert 'x' to IndexedSlices. Convert a dense Tensor to a block-sparse IndexedSlices. Args: x: Either a Tensor object, or an IndexedSlices object. optimize: if true, attempt to optimize the conversion of 'x'. Returns: An IndexedSlices object. Raises...
2,583
2,604
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
_as_indexed_slices_list
Convert all elements of 'inputs' to IndexedSlices. Additionally, homogenize the types of all the indices to either int32 or int64. Args: inputs: List containing either Tensor or IndexedSlices objects. optimize: if true, attempt to optimize the conversion of each input. Returns: A list of IndexedSlices objects....
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
def _as_indexed_slices_list(inputs, optimize=True): """Convert all elements of 'inputs' to IndexedSlices. Additionally, homogenize the types of all the indices to either int32 or int64. Args: inputs: List containing either Tensor or IndexedSlices objects. optimize: if true, attempt to optimize the con...
2,607
2,639
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
add_n
Adds all input tensors element-wise. Converts `IndexedSlices` objects into dense tensors prior to adding. Args: inputs: A list of `Tensor` or `IndexedSlices` objects, each with same shape and type. name: A name for the operation (optional). Returns: A `Tensor` of same shape and type as the elements of `inp...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export("math.add_n", "add_n") @dispatch.add_dispatch_support def add_n(inputs, name=None): """Adds all input tensors element-wise. Converts `IndexedSlices` objects into dense tensors prior to adding. Args: inputs: A list of `Tensor` or `IndexedSlices` objects, each with same shape and type. na...
2,642
2,677
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
accumulate_n
Returns the element-wise sum of a list of tensors. Optionally, pass `shape` and `tensor_dtype` for shape and type checking, otherwise, these are inferred. `tf.math.accumulate_n` performs the same operation as `tf.add_n`, but does not wait for all of its inputs to be ready before beginning to sum. This can save memory...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
@tf_export("math.accumulate_n", v1=["math.accumulate_n", "accumulate_n"]) @deprecation.deprecated_endpoints("accumulate_n") def accumulate_n(inputs, shape=None, tensor_dtype=None, name=None): """Returns the element-wise sum of a list of tensors. Optionally, pass `shape` and `tensor_dtype` for shape and type checki...
2,680
2,757
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
reduced_shape
Helper function for reduction ops. Args: input_shape: 1-D Tensor, the shape of the Tensor being reduced. axes: 1-D Tensor, the reduction axes. Returns: A 1-D Tensor, the output shape as if keepdims were set to True.
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
def reduced_shape(input_shape, axes): """Helper function for reduction ops. Args: input_shape: 1-D Tensor, the shape of the Tensor being reduced. axes: 1-D Tensor, the reduction axes. Returns: A 1-D Tensor, the output shape as if keepdims were set to True. """ # Example: # cast needed for Spars...
3,053
3,084
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
read_zfile
Read the z-file and return the content as a string Z-files are raw data compressed with zlib used internally by joblib for persistence. Backward compatibility is not guaranteed. Do not use for external purposes.
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
def read_zfile(file_handle): """Read the z-file and return the content as a string Z-files are raw data compressed with zlib used internally by joblib for persistence. Backward compatibility is not guaranteed. Do not use for external purposes. """ file_handle.seek(0) assert _read_magic(file...
61
93
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
write_zfile
Write the data in the given file as a Z-file. Z-files are raw data compressed with zlib used internally by joblib for persistence. Backward compatibility is not guarantied. Do not use for external purposes.
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
def write_zfile(file_handle, data, compress=1): """Write the data in the given file as a Z-file. Z-files are raw data compressed with zlib used internally by joblib for persistence. Backward compatibility is not guarantied. Do not use for external purposes. """ file_handle.write(_ZFILE_PREFIX) ...
96
107
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
dump
Fast persistence of an arbitrary Python object into one or multiple files, with dedicated storage for numpy arrays. Parameters ----------- value: any Python object The object to store to disk filename: string The name of the file in which it is to be stored compress: integer for 0 to 9, optional Optional c...
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
def dump(value, filename, compress=0, cache_size=100, protocol=None): """Fast persistence of an arbitrary Python object into one or multiple files, with dedicated storage for numpy arrays. Parameters ----------- value: any Python object The object to store to disk filename: string ...
348
409
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
load_build
This method is called to set the state of a newly created object. We capture it to replace our place-holder objects, NDArrayWrapper, by the array we are interested in. We replace them directly in the stack of pickler.
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
def load_build(self): """ This method is called to set the state of a newly created object. We capture it to replace our place-holder objects, NDArrayWrapper, by the array we are interested in. We replace them directly in the stack of pickler. """ ...
308
323
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
filter_by_size
[deprecated] Filter indices based on their size. Use `FairseqDataset::filter_indices_by_size` instead. Args: indices (List[int]): ordered list of dataset indices dataset (FairseqDataset): fairseq dataset instance max_positions (tuple): filter elements larger than this size. Comparisons are done com...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
def filter_by_size(indices, dataset, max_positions, raise_exception=False): """ [deprecated] Filter indices based on their size. Use `FairseqDataset::filter_indices_by_size` instead. Args: indices (List[int]): ordered list of dataset indices dataset (FairseqDataset): fairseq dataset ins...
193
243
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
filter_paired_dataset_indices_by_size
Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max sample size, can be defined separately for src and tgt (then list or tuple) Returns: np.array: f...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes): """Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max s...
246
279
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
batch_by_size
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index num_tokens_vec (List[int], optional): precomputed vect...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
def batch_by_size( indices, num_tokens_fn, num_tokens_vec=None, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, fixed_shapes=None, ): """ Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: in...
282
365
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
main
Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: str
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script to upload the mappings of Freebase to Wikidata. Can be easily adapted to upload other String identifiers as well This bot needs the dump from https://developers.google.com/freebase/data#freebase-wikidata-mappings The script takes a single parameter: -filename: th...
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: str """ filename = 'fb2w.nt.gz' # Default filename for arg in pywikibot.handle_args(args): if arg.startswith('-filena...
107
121
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script to upload the mappings of Freebase to Wikidata. Can be easily adapted to upload other String identifiers as well This bot needs the dump from https://developers.google.com/freebase/data#freebase-wikidata-mappings The script takes a single parameter: -filename: th...
run
On purpose this doesn't call the ObjectDescription version, but is based on it. Each alias signature may expand into multiple real signatures (an overload set). The code is therefore based on the ObjectDescription version.
""" sphinx.domains.cpp ~~~~~~~~~~~~~~~~~~ The C++ language domain. :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from typing import ( Any, Callable, Dict, Generator, Iterator, List, Tuple, Type, TypeVar, Union ) from do...
def run(self) -> List[Node]: """ On purpose this doesn't call the ObjectDescription version, but is based on it. Each alias signature may expand into multiple real signatures (an overload set). The code is therefore based on the ObjectDescription version. """ if ':' i...
6,818
6,847
""" sphinx.domains.cpp ~~~~~~~~~~~~~~~~~~ The C++ language domain. :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from typing import ( Any, Callable, Dict, Generator, Iterator, List, Tuple, Type, TypeVar, Union ) from do...
get
Get an existing WebAppSitePushSettingsSlot resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOption...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'WebAppSitePushSettingsSlot': """ Get an existing WebAppSitePushSettingsSlot resource's state with the given name, id, and optional extra properties ...
90
114
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
on_help
Bring up the Kiessig fringe calculator Documentation whenever the HELP button is clicked. Calls DocumentationWindow with the path of the location within the documentation tree (after /doc/ ....". Note that when using old versions of Wx (before 2.9) and thus not the release version of installers...
""" This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. See the license text in license.txt copyright 2008, 2009, University of Tennessee """ import wx import sys from sas....
def on_help(self, event): """ Bring up the Kiessig fringe calculator Documentation whenever the HELP button is clicked. Calls DocumentationWindow with the path of the location within the documentation tree (after /doc/ ....". Note that when using old versions of Wx (...
161
177
""" This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. See the license text in license.txt copyright 2008, 2009, University of Tennessee """ import wx import sys from sas....
blend
Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than 1.0 "extrapolates" the difference between the t...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than...
150
190
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
rotate
Rotates the image by degrees either clockwise or counterclockwise. Args: image: An image Tensor of type uint8. degrees: Float, a scalar angle in degrees to rotate all images by. If degrees is positive the image will be rotated clockwise otherwise it will be rotated counterclockwise. replace: A one or thr...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
def rotate(image, degrees, replace): """Rotates the image by degrees either clockwise or counterclockwise. Args: image: An image Tensor of type uint8. degrees: Float, a scalar angle in degrees to rotate all images by. If degrees is positive the image will be rotated clockwise otherwise it will ...
295
317
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
_clip_bbox
Clip bounding box coordinates between 0 and 1. Args: min_y: Normalized bbox coordinate of type float between 0 and 1. min_x: Normalized bbox coordinate of type float between 0 and 1. max_y: Normalized bbox coordinate of type float between 0 and 1. max_x: Normalized bbox coordinate of type float between 0 and 1...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
def _clip_bbox(min_y, min_x, max_y, max_x): """Clip bounding box coordinates between 0 and 1. Args: min_y: Normalized bbox coordinate of type float between 0 and 1. min_x: Normalized bbox coordinate of type float between 0 and 1. max_y: Normalized bbox coordinate of type float between 0 and 1. max_...
435
451
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
_rotate_bbox
Rotates the bbox coordinated by degrees. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, height of the image. degrees: Float, a scalar angle in degrees ...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
def _rotate_bbox(bbox, image_height, image_width, degrees): """Rotates the bbox coordinated by degrees. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_wi...
785
835
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
_shift_bbox
Shifts the bbox coordinates by pixels. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, width of the image. pixels: An int. How many pixels to shift the ...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
def _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal): """Shifts the bbox coordinates by pixels. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image...
881
919
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
_shear_bbox
Shifts the bbox according to how the image was sheared. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, height of the image. level: Float. How much to s...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
def _shear_bbox(bbox, image_height, image_width, level, shear_horizontal): """Shifts the bbox according to how the image was sheared. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, hei...
978
1,025
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
distort_image_with_autoaugment
Applies the AutoAugment policy to `image` and `bboxes`. Args: image: `Tensor` of shape [height, width, 3] representing an image. bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are normalized between [0, 1]. augmentation_name: The name of the AutoAugment policy to use. The available ...
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
@tf.autograph.experimental.do_not_convert def distort_image_with_autoaugment(image, bboxes, augmentation_name): """Applies the AutoAugment policy to `image` and `bboxes`. Args: image: `Tensor` of shape [height, width, 3] representing an imag...
1,591
1,629
# Copyright 2020 Google Research. All Rights Reserved. # # 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...
get_hgmo_archive
An archiver for hg.mozilla.org related requests. Uses relengapi.blueprints.archiver.get_archive :param repo: the repo location off of hg.mozilla.org/ :param rev: the rev associated with the repo :param subdir: optional subdir path to only archive a portion of the repo :param suffix: the archive extension type. default...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import logging import datetime import sqlalchemy as sa from random import randint from flask import Blueprint from f...
@bp.route('/hgmo/<path:repo>/<rev>') @api.apimethod(None, unicode, unicode, unicode, unicode, unicode, status_code=302) def get_hgmo_archive(repo, rev, subdir=None, suffix='tar.gz', preferred_region=None): """ An archiver for hg.mozilla.org related requests. Uses relengapi.blueprints.archiver.get_archive :...
124
147
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import logging import datetime import sqlalchemy as sa from random import randint from flask import Blueprint from f...
is_absolute_uri
Returns True if the parsed result is an "absolute URI". We define an "absolute URI" as containing at mimimum a **scheme** and an **host** (a.k.a., an authority). It must contain SH according to the nomenclature defined in this proposal: https://gist.github.com/andrewdotn/eebeaa60d48c3c0f6f9fc75f0ede8d03#proposal Exa...
""" Get absolute URLs for static assets. """ from urllib.parse import ParseResult, urlparse, urlunparse from django import template from django.templatetags.static import StaticNode from django.urls import reverse register = template.Library() class AbstaticNode(StaticNode): """ {% abstatic %} is like Djan...
def is_absolute_uri(url: ParseResult) -> bool: """ Returns True if the parsed result is an "absolute URI". We define an "absolute URI" as containing at mimimum a **scheme** and an **host** (a.k.a., an authority). It must contain SH according to the nomenclature defined in this proposal: https:...
34
65
""" Get absolute URLs for static assets. """ from urllib.parse import ParseResult, urlparse, urlunparse from django import template from django.templatetags.static import StaticNode from django.urls import reverse register = template.Library() class AbstaticNode(StaticNode): """ {% abstatic %} is like Djan...
test_can_add_gates_into_free_space
The scheduler does some time bookkeeping to know when qubits are free to be scheduled. Make sure this works for qubits that are used in the future. This was a bug, uncovered by this example: q0 = - - - - |X| q1 = |X| |u2| |X| In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather than i...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
def test_can_add_gates_into_free_space(self): """The scheduler does some time bookkeeping to know when qubits are free to be scheduled. Make sure this works for qubits that are used in the future. This was a bug, uncovered by this example: q0 = - - - - |X| q1 = |X| |u...
221
246
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
default_data_collator
Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - ``label``: handles a single value (int or float) per object - ``label_ids``: handles a list of values per object Does not do any additional preprocessing: property names of the...
# Copyright 2020 The HuggingFace Team. All rights reserved. # # 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 applicabl...
def default_data_collator(features: List[InputDataClass]) -> Dict[str, torch.Tensor]: """ Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - ``label``: handles a single value (int or float) per object - ``lab...
38
83
# Copyright 2020 The HuggingFace Team. All rights reserved. # # 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 applicabl...
_search_table
Call the search service endpoint and return matching results Search service logic defined here: https://github.com/lyft/amundsensearchlibrary/blob/master/search_service/api/table.py :return: a json output containing search results array as 'results'
import logging import json from http import HTTPStatus from typing import Any, Dict # noqa: F401 from flask import Response, jsonify, make_response, request from flask import current_app as app from flask.blueprints import Blueprint from amundsen_application.log.action_log import action_logging from amundsen_appli...
@action_logging def _search_table(*, search_term: str, page_index: int, filters: Dict, search_type: str) -> Dict[str, Any]: """ Call the search service endpoint and return matching results Search service logic defined here: https://github.com/lyft/amundsensearchlibrary/blob/master/search_service/api/tab...
56
108
import logging import json from http import HTTPStatus from typing import Any, Dict # noqa: F401 from flask import Response, jsonify, make_response, request from flask import current_app as app from flask.blueprints import Blueprint from amundsen_application.log.action_log import action_logging from amundsen_appli...
_search_user
Call the search service endpoint and return matching results Search service logic defined here: https://github.com/lyft/amundsensearchlibrary/blob/master/search_service/api/user.py :return: a json output containing search results array as 'results'
import logging import json from http import HTTPStatus from typing import Any, Dict # noqa: F401 from flask import Response, jsonify, make_response, request from flask import current_app as app from flask.blueprints import Blueprint from amundsen_application.log.action_log import action_logging from amundsen_appli...
@action_logging def _search_user(*, search_term: str, page_index: int, search_type: str) -> Dict[str, Any]: """ Call the search service endpoint and return matching results Search service logic defined here: https://github.com/lyft/amundsensearchlibrary/blob/master/search_service/api/user.py :retur...
131
184
import logging import json from http import HTTPStatus from typing import Any, Dict # noqa: F401 from flask import Response, jsonify, make_response, request from flask import current_app as app from flask.blueprints import Blueprint from amundsen_application.log.action_log import action_logging from amundsen_appli...
start
Start the background coroutine to balance the tasks on the cluster. Idempotent. The scheduler argument is ignored. It is merely required to satisify the plugin interface. Since this class is simultaneouly an extension, the scheudler instance is already registered during initialization
from __future__ import annotations import asyncio import logging from collections import defaultdict, deque from math import log2 from time import time from typing import Container from tlz import topk from tornado.ioloop import PeriodicCallback import dask from dask.utils import parse_timedelta from .comm.addressi...
async def start(self, scheduler=None): """Start the background coroutine to balance the tasks on the cluster. Idempotent. The scheduler argument is ignored. It is merely required to satisify the plugin interface. Since this class is simultaneouly an extension, the scheudler i...
84
98
from __future__ import annotations import asyncio import logging from collections import defaultdict, deque from math import log2 from time import time from typing import Container from tlz import topk from tornado.ioloop import PeriodicCallback import dask from dask.utils import parse_timedelta from .comm.addressi...
is_noncomplex
Returns True if *obj* is a special (weird) class, that is more complex than primitive data types, but is not a full object. Including: * :class:`~time.struct_time`
# Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Helper functions for pickling and unpickling...
def is_noncomplex(obj): """Returns True if *obj* is a special (weird) class, that is more complex than primitive data types, but is not a full object. Including: * :class:`~time.struct_time` """ if type(obj) is time.struct_time: return True return False
250
258
# Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Helper functions for pickling and unpickling...
importable_name
>>> class Example(object): ... pass >>> ex = Example() >>> importable_name(ex.__class__) == 'jsonpickle.util.Example' True >>> importable_name(type(25)) == 'builtins.int' True >>> importable_name(None.__class__) == 'builtins.NoneType' True >>> importable_name(False.__class__) == 'builtins.bool' True >>> importable...
# Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Helper functions for pickling and unpickling...
def importable_name(cls): """ >>> class Example(object): ... pass >>> ex = Example() >>> importable_name(ex.__class__) == 'jsonpickle.util.Example' True >>> importable_name(type(25)) == 'builtins.int' True >>> importable_name(None.__class__) == 'builtins.NoneType' True >...
513
534
# Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Helper functions for pickling and unpickling...
__init__
Init crea :param str node: Node to connect to *(optional)* :param str rpcuser: RPC user *(optional)* :param str rpcpassword: RPC password *(optional)* :param bool nobroadcast: Do **not** broadcast a transaction! *(optional)* :param bool unsigned: Do **not** sign a transaction! *(optional)* :param bool debug: Enabl...
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def __init__(self, node="", rpcuser=None, rpcpassword=None, debug=False, data_refresh_time_seconds=900, **kwargs): """Init crea :param str node: Node to connect to *(optional)* :par...
133
214
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
get_reward_funds
Get details for a reward fund. :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used.
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def get_reward_funds(self, use_stored_data=True): """ Get details for a reward fund. :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used. """ if use_stored_data: self.refresh_dat...
333
359
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
get_crea_per_mvest
Returns the MVEST to CREA ratio :param int time_stamp: (optional) if set, return an estimated CREA per MVEST ratio for the given time stamp. If unset the current ratio is returned (default). (can also be a datetime object)
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def get_crea_per_mvest(self, time_stamp=None, use_stored_data=True): """ Returns the MVEST to CREA ratio :param int time_stamp: (optional) if set, return an estimated CREA per MVEST ratio for the given time stamp. If unset the current ratio is returned (default)....
532
556
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
sbd_to_vote_pct
Obtain the voting percentage for a desired CBD value for a given Crea Power or vesting shares and voting power Give either Crea Power or vests, not both. When the output is greater than 10000 or smaller than -10000, the CBD value is too high. Returns the required voting percentage (100% = 10000) :param sbd: desired C...
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def sbd_to_vote_pct(self, sbd, crea_power=None, vests=None, voting_power=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): """ Obtain the voting percentage for a desired CBD value for a given Crea Power or vesting shares and voting power Give either Crea Power or ve...
728
755
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
claim_account
Claim account for claimed account creation. When fee is 0 CREA a subsidized account is claimed and can be created later with create_claimed_account. The number of subsidized account is limited. :param str creator: which account should pay the registration fee (RC or CREA) (defaults to ``default_account``) :pa...
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def claim_account(self, creator, fee=None, **kwargs): """ Claim account for claimed account creation. When fee is 0 CREA a subsidized account is claimed and can be created later with create_claimed_account. The number of subsidized account is limited. :param...
1,049
1,074
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
custom_json
Create a custom json operation :param str id: identifier for the custom json (max length 32 bytes) :param json json_data: the json data to put into the custom_json operation :param list required_auths: (optional) required auths :param list required_posting_auths: (optional) posting auths .. note:: While reqired a...
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def custom_json(self, id, json_data, required_auths=[], required_posting_auths=[], **kwargs): """ Create a custom json operation :param str id: identifier for the custom json (max length 32 bytes...
1,567
1,607
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
comment_options
Set the comment options :param dict options: The options to define. :param str identifier: Post identifier :param list beneficiaries: (optional) list of beneficiaries :param str account: (optional) the account to allow access to (defaults to ``default_account``) For the options, you have these defaults::: { ...
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
def comment_options(self, options, identifier, beneficiaries=[], account=None, **kwargs): """ Set the comment options :param dict options: The options to define. :param str identifier: Post identifier :param list beneficiaries: (optional) list of ...
1,814
1,844
# This Python file uses the following encoding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from builtins import object import json import logging import re import os import math impor...
check_closed_path
Checks that data is not changed for the first closed path found. Returns True if data==data after moving around the closed path, False otherwise. Starting point is current_node
#----------------------------------------------------------------------------- # Name: GraphModels # Purpose: To store graphs used in network translations # Author: Aric Sanders # Created: 4/6/2016 # License: MIT License #--------------------------------------------------------------------------...
def check_closed_path(self): """Checks that data is not changed for the first closed path found. Returns True if data==data after moving around the closed path, False otherwise. Starting point is current_node """ temp_data = self.data path = self.get_path(self.current_node, self.curr...
615
629
#----------------------------------------------------------------------------- # Name: GraphModels # Purpose: To store graphs used in network translations # Author: Aric Sanders # Created: 4/6/2016 # License: MIT License #--------------------------------------------------------------------------...