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
format_excitation_indices
Consistent formatting of excitation indices idx = [(p0,q0),(p1,q1),...,(pn,qn)] sorted as: p0<p1<pn and pi<qi :param idx: list of index tuples describing a single(!) fermionic excitation :return: tuple-list of index tuples
import os from dataclasses import dataclass from tequila import TequilaException, BitString, TequilaWarning from tequila.hamiltonian import QubitHamiltonian from tequila.wavefunction import QubitWaveFunction from tequila.hamiltonian.paulis import Sp, Sm, Qp, Qm from tequila.circuit import QCircuit, gates, _gates_impl ...
def format_excitation_indices(self, idx): """ Consistent formatting of excitation indices idx = [(p0,q0),(p1,q1),...,(pn,qn)] sorted as: p0<p1<pn and pi<qi :param idx: list of index tuples describing a single(!) fermionic excitation :return: tuple-list of index tuples...
1,205
1,216
import os from dataclasses import dataclass from tequila import TequilaException, BitString, TequilaWarning from tequila.hamiltonian import QubitHamiltonian from tequila.wavefunction import QubitWaveFunction from tequila.hamiltonian.paulis import Sp, Sm, Qp, Qm from tequila.circuit import QCircuit, gates, _gates_impl ...
compute_mp2_amplitudes
Compute closed-shell mp2 amplitudes .. math:: t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) ) :return: Parameters ---------- Returns -------
import os from dataclasses import dataclass from tequila import TequilaException, BitString, TequilaWarning from tequila.hamiltonian import QubitHamiltonian from tequila.wavefunction import QubitWaveFunction from tequila.hamiltonian.paulis import Sp, Sm, Qp, Qm from tequila.circuit import QCircuit, gates, _gates_impl ...
def compute_mp2_amplitudes(self) -> ClosedShellAmplitudes: """ Compute closed-shell mp2 amplitudes .. math:: t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) ) :return: Parameters ---------- Returns ------- """ ...
1,592
1,621
import os from dataclasses import dataclass from tequila import TequilaException, BitString, TequilaWarning from tequila.hamiltonian import QubitHamiltonian from tequila.wavefunction import QubitWaveFunction from tequila.hamiltonian.paulis import Sp, Sm, Qp, Qm from tequila.circuit import QCircuit, gates, _gates_impl ...
goal_conditions_for_demo
Infer the goal conditions of a single demonstration. Args ---- demo: the demonstration to infer the goal of. behavior: check the behavior to remove conflicting conditions. Returns ------- goals: list of the goals inferred in the demonstration.
"""Module containing methods that allow to identify task goals.""" # Copyright (c) 2022, ABB # All rights reserved. # # Redistribution and use in source and binary forms, with # or without modification, are permitted provided that # the following conditions are met: # # * Redistributions of source code must retain t...
def goal_conditions_for_demo( demo: Demonstration, behaviors: Any ) -> List[str]: """ Infer the goal conditions of a single demonstration. Args ---- demo: the demonstration to infer the goal of. behavior: check the behavior to remove conflicting conditions. Returns ----...
42
66
"""Module containing methods that allow to identify task goals.""" # Copyright (c) 2022, ABB # All rights reserved. # # Redistribution and use in source and binary forms, with # or without modification, are permitted provided that # the following conditions are met: # # * Redistributions of source code must retain t...
_save_custom_objects
Save custom objects dictionary to a cloudpickle file so a model can be easily loaded later. :param path: An absolute path that points to the data directory within /path/to/model. :param custom_objects: Keras ``custom_objects`` is a dictionary mapping names (strings) to custom classes or function...
""" The ``mlflow.keras`` module provides an API for logging and loading Keras models. This module exports Keras models with the following flavors: Keras (native) format This is the main flavor that can be loaded back into Keras. :py:mod:`mlflow.pyfunc` Produced for use by generic pyfunc-based deployment tools ...
def _save_custom_objects(path, custom_objects): """ Save custom objects dictionary to a cloudpickle file so a model can be easily loaded later. :param path: An absolute path that points to the data directory within /path/to/model. :param custom_objects: Keras ``custom_objects`` is a dictionary mapping ...
318
333
""" The ``mlflow.keras`` module provides an API for logging and loading Keras models. This module exports Keras models with the following flavors: Keras (native) format This is the main flavor that can be loaded back into Keras. :py:mod:`mlflow.pyfunc` Produced for use by generic pyfunc-based deployment tools ...
_load_pyfunc
Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``. :param path: Local filesystem path to the MLflow Model with the ``keras`` flavor.
""" The ``mlflow.keras`` module provides an API for logging and loading Keras models. This module exports Keras models with the following flavors: Keras (native) format This is the main flavor that can be loaded back into Keras. :py:mod:`mlflow.pyfunc` Produced for use by generic pyfunc-based deployment tools ...
def _load_pyfunc(path): """ Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``. :param path: Local filesystem path to the MLflow Model with the ``keras`` flavor. """ import tensorflow as tf if os.path.isfile(os.path.join(path, _KERAS_MODULE_SPEC_PATH)): with open(os.path.join(...
381
414
""" The ``mlflow.keras`` module provides an API for logging and loading Keras models. This module exports Keras models with the following flavors: Keras (native) format This is the main flavor that can be loaded back into Keras. :py:mod:`mlflow.pyfunc` Produced for use by generic pyfunc-based deployment tools ...
_from_ordinalf
Convert Gregorian float of the date, preserving hours, minutes, seconds and microseconds. Return value is a :class:`datetime`. The input date `x` is a float in ordinal days at UTC, and the output will be the specified :class:`datetime` object corresponding to that time in timezone `tz`, or if `tz` is `None`, in the t...
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def _from_ordinalf(x, tz=None): """ Convert Gregorian float of the date, preserving hours, minutes, seconds and microseconds. Return value is a :class:`datetime`. The input date `x` is a float in ordinal days at UTC, and the output will be the specified :class:`datetime` object corresponding to th...
257
284
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
num2date
*x* is a float value which gives the number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC *plus* *one*. The addition of one here is a historical artifact. Also, note that the Gregorian calendar is assumed; this is not universal practice. For details, see the module docstring...
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def num2date(x, tz=None): """ *x* is a float value which gives the number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC *plus* *one*. The addition of one here is a historical artifact. Also, note that the Gregorian calendar is assumed; this is not univ...
401
424
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
drange
Return a date range as float Gregorian ordinals. *dstart* and *dend* are :class:`datetime` instances. *delta* is a :class:`datetime.timedelta` instance.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def drange(dstart, dend, delta): """ Return a date range as float Gregorian ordinals. *dstart* and *dend* are :class:`datetime` instances. *delta* is a :class:`datetime.timedelta` instance. """ f1 = _to_ordinalf(dstart) f2 = _to_ordinalf(dend) step = _total_seconds(delta) / SEC_PER_DAY...
427
450
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
_replace_common_substr
Helper function for replacing substrings sub1 and sub2 located at the same indexes in strings s1 and s2 respectively, with the string replacement. It is expected that sub1 and sub2 have the same length. Returns the pair s1, s2 after the substitutions.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def _replace_common_substr(self, s1, s2, sub1, sub2, replacement): """Helper function for replacing substrings sub1 and sub2 located at the same indexes in strings s1 and s2 respectively, with the string replacement. It is expected that sub1 and sub2 have the same length. Returns t...
490
513
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
strftime_pre_1900
Call time.strftime for years before 1900 by rolling forward a multiple of 28 years. *fmt* is a :func:`strftime` format string. Dalke: I hope I did this math right. Every 28 years the calendar repeats, except through century leap years excepting the 400 year leap years. But only if you're using the Gregorian calenda...
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def strftime_pre_1900(self, dt, fmt=None): """Call time.strftime for years before 1900 by rolling forward a multiple of 28 years. *fmt* is a :func:`strftime` format string. Dalke: I hope I did this math right. Every 28 years the calendar repeats, except through century lea...
515
570
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
strftime
Refer to documentation for datetime.strftime. *fmt* is a :func:`strftime` format string. Warning: For years before 1900, depending upon the current locale it is possible that the year displayed with %x might be incorrect. For years before 100, %y and %Y will yield zero-padded strings.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def strftime(self, dt, fmt=None): """Refer to documentation for datetime.strftime. *fmt* is a :func:`strftime` format string. Warning: For years before 1900, depending upon the current locale it is possible that the year displayed with %x might be incorrect. For years befor...
572
591
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
__init__
Autoformat the date labels. The default format is the one to use if none of the values in ``self.scaled`` are greater than the unit returned by ``locator._get_unit()``.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d'): """ Autoformat the date labels. The default format is the one to use if none of the values in ``self.scaled`` are greater than the unit returned by ``locator._get_unit()``. """ self._locator = locator ...
678
692
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
__init__
Mark every month in *bymonth*; *bymonth* can be an int or sequence. Default is ``range(1,13)``, i.e. every month. *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurance.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None): """ Mark every month in *bymonth*; *bymonth* can be an int or sequence. Default is ``range(1,13)``, i.e. every month. *interval* is the interval between each iteration. For example, if ``interval=2``, mar...
1,204
1,222
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
__init__
Mark every hour in *byhour*; *byhour* can be an int or sequence. Default is to tick every hour: ``byhour=range(24)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurrence.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def __init__(self, byhour=None, interval=1, tz=None): """ Mark every hour in *byhour*; *byhour* can be an int or sequence. Default is to tick every hour: ``byhour=range(24)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every secon...
1,282
1,295
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
__init__
Mark every minute in *byminute*; *byminute* can be an int or sequence. Default is to tick every minute: ``byminute=range(60)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurrence.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def __init__(self, byminute=None, interval=1, tz=None): """ Mark every minute in *byminute*; *byminute* can be an int or sequence. Default is to tick every minute: ``byminute=range(60)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mar...
1,302
1,315
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
__init__
Mark every second in *bysecond*; *bysecond* can be an int or sequence. Default is to tick every second: ``bysecond = range(60)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurrence.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def __init__(self, bysecond=None, interval=1, tz=None): """ Mark every second in *bysecond*; *bysecond* can be an int or sequence. Default is to tick every second: ``bysecond = range(60)`` *interval* is the interval between each iteration. For example, if ``interval=2``, m...
1,322
1,335
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
__init__
*interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
def __init__(self, interval=1, tz=None): """ *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond. """ self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) self.tz = tz
1,343
1,351
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
axisinfo
Return the :class:`~matplotlib.units.AxisInfo` for *unit*. *unit* is a tzinfo instance or None. The *axis* argument is required but not used.
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
@staticmethod def axisinfo(unit, axis): """ Return the :class:`~matplotlib.units.AxisInfo` for *unit*. *unit* is a tzinfo instance or None. The *axis* argument is required but not used. """ tz = unit majloc = AutoDateLocator(tz=tz) majfmt = AutoD...
1,525
1,541
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
start
Start the reflection process! We'll do a blocking read of all resources first, so that we don't race with any operations that are checking the state of the pod store - such as polls. This should be called only once at the start of program initialization (when the singleton is being created), and not afterwards!
# specifically use concurrent.futures for threadsafety # asyncio Futures cannot be used across threads import asyncio import json import time from functools import partial from kubernetes_asyncio import watch from traitlets import Any from traitlets import Bool from traitlets import Dict from traitlets import Int from...
async def start(self): """ Start the reflection process! We'll do a blocking read of all resources first, so that we don't race with any operations that are checking the state of the pod store - such as polls. This should be called only once at the start of program i...
378
392
# specifically use concurrent.futures for threadsafety # asyncio Futures cannot be used across threads import asyncio import json import time from functools import partial from kubernetes_asyncio import watch from traitlets import Any from traitlets import Bool from traitlets import Dict from traitlets import Int from...
labels_to_one_hot
Convert 1D array of labels to one hot representation Args: labels: 1D numpy array
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file. # Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug) import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' from models import DenseNet from data_providers.utils import...
def labels_to_one_hot(labels, n_classes=43+1): """Convert 1D array of labels to one hot representation Args: labels: 1D numpy array """ new_labels = np.zeros((n_classes,)) new_labels[labels] = 1 return new_labels
81
89
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file. # Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug) import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' from models import DenseNet from data_providers.utils import...
trajectory_4way
Generate trajectory of agent diffusing through 4-way connected graph At each point we sample the one-hot observation and take an action 0 = up 1 = right 2 = down 3 = left Params: steps (int): Number of steps to take env (3d np array): environment in which to wander (NxNx(num_categories)) Returns Observat...
import os import sys import numpy as np import torch import pickle import logging log = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) class Graph4D(): def __init__(self, num_envs=4096...
def trajectory_4way(self, env): """ Generate trajectory of agent diffusing through 4-way connected graph At each point we sample the one-hot observation and take an action 0 = up 1 = right 2 = down 3 = left Params: steps (int): Number of ...
93
121
import os import sys import numpy as np import torch import pickle import logging log = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) class Graph4D(): def __init__(self, num_envs=4096...
generate_data
Generates N square environments and trajectories ((observation, action) pairs) for each environment Params: envs (int): number of environments to generate steps (int): how many steps an agent initially takes in each environment env_size (tuple): size of environment (should be something like (4,4), (9,9), e...
import os import sys import numpy as np import torch import pickle import logging log = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) class Graph4D(): def __init__(self, num_envs=4096...
def generate_data(self, verbose=False): """ Generates N square environments and trajectories ((observation, action) pairs) for each environment Params: envs (int): number of environments to generate steps (int): how many steps an agent initially takes in each...
123
162
import os import sys import numpy as np import torch import pickle import logging log = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) class Graph4D(): def __init__(self, num_envs=4096...
control
Return a (mutli-)controlled-RX gate. Args: num_ctrl_qubits (int): number of control qubits. label (str or None): An optional label for the gate [Default: None] ctrl_state (int or str or None): control state expressed as integer, string (e.g. '110'), or None. If None, use all 1s. Returns: Contr...
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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 modifications or derivative wo...
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RX gate. Args: num_ctrl_qubits (int): number of control qubits. label (str or None): An optional label for the gate [Default: None] ctrl_state (int or str or None): ...
66
82
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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 modifications or derivative wo...
lookup
Looks up a specific information value based on either a string pattern or a path. For example, the pattern "stats.roc_auc.labels.true" is the same as the path ``['stats', 'roc_auc', 'labels', True]``. :Parameters: path : `str` | `list` The location of the information to lookup.
from collections import OrderedDict from . import util from ..errors import ModelInfoLookupError class ModelInfo: def __init__(self, pairs=[], default_fields=None): """ Constructs a mapping of information about a model. :class:`~revscoring.scoring.ModelInfo` objects are usually nested ...
def lookup(self, path=None): """ Looks up a specific information value based on either a string pattern or a path. For example, the pattern "stats.roc_auc.labels.true" is the same as the path ``['stats', 'roc_auc', 'labels', True]``. :Parameters: path : ...
56
83
from collections import OrderedDict from . import util from ..errors import ModelInfoLookupError class ModelInfo: def __init__(self, pairs=[], default_fields=None): """ Constructs a mapping of information about a model. :class:`~revscoring.scoring.ModelInfo` objects are usually nested ...
_quote_str
Escape all unicode characters to there unicode code points in form of \uxxxx. The returned string is a pure ascii string. Normal ascii characters like \n or \t won't be escaped. note: wxGlade don't handles file encoding well currently. Thereby we escape all unicode characters. note: The string 's' is encoded wi...
"""\ Perl code generator @copyright: 2002-2004 D.H. aka crazyinsomniac on sourceforge.net @copyright: 2012-2016 Carsten Grohmann @copyright: 2017-2020 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import os, os.path, re from codegen import BaseLangCodeWriter, BaseSour...
def _quote_str(self, s): """Escape all unicode characters to there unicode code points in form of \\uxxxx. The returned string is a pure ascii string. Normal ascii characters like \\n or \\t won't be escaped. note: wxGlade don't handles file encoding well currently. Thereby ...
462
504
"""\ Perl code generator @copyright: 2002-2004 D.H. aka crazyinsomniac on sourceforge.net @copyright: 2012-2016 Carsten Grohmann @copyright: 2017-2020 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import os, os.path, re from codegen import BaseLangCodeWriter, BaseSour...
disk_image_batch_dataset
Disk image batch dataset. This function is suitable for jpg and png files Arguments: img_paths : String list or 1-D tensor, each of which is an iamge path labels : Label list/tuple_of_list or tensor/tuple_of_tensor, each of which is a corresponding label
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing from functools import partial import tensorflow as tf import tensorflow.contrib.eager as tfe from general.utilTF1.utils import session from general.kneeOsteoarthritisDataset.KneeOsteoart...
def disk_image_batch_dataset(img_paths, batch_size, labels=None, prefetch_batch=_N_CPU + 1, drop_remainder=True, filter=None, map_func=None, num_threads=_N_CPU, shuffle=True, buffer_size=4096, repeat=-1): """Disk image batch dataset. This function is suitable for jpg and png files ...
136
169
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing from functools import partial import tensorflow as tf import tensorflow.contrib.eager as tfe from general.utilTF1.utils import session from general.kneeOsteoarthritisDataset.KneeOsteoart...
compute_many
Compute ROUGE score between guess and *any* answer. Done with compute_many due to increased efficiency. :return: (rouge-1, rouge-2, rouge-L)
#!/usr/bin/env python3 # 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. """ Provides standard metric evaluations for dialog. Uses locking and shared memory when ``numthreads`` is set to >1 to ...
@staticmethod def compute_many( guess: str, answers: List[str] ) -> Tuple[ Optional['RougeMetric'], Optional['RougeMetric'], Optional['RougeMetric'] ]: """ Compute ROUGE score between guess and *any* answer. Done with compute_many due to increased efficiency. ...
491
533
#!/usr/bin/env python3 # 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. """ Provides standard metric evaluations for dialog. Uses locking and shared memory when ``numthreads`` is set to >1 to ...
get
Get values according to the filepath. Args: filepath (str | obj:`Path`): Here, filepath is the lmdb key.
import inspect import warnings from abc import ABCMeta, abstractmethod from mmcv_custom.fileio.zipreader import ZipReader class BaseStorageBackend(metaclass=ABCMeta): """Abstract class of storage backends. All backends need to implement two apis: `get()` and `get_text()`. `get()` reads the file as a byte ...
def get(self, filepath): """Get values according to the filepath. Args: filepath (str | obj:`Path`): Here, filepath is the lmdb key. """ filepath = str(filepath) with self._client.begin(write=False) as txn: value_buf = txn.get(filepath.encode('ascii')...
164
173
import inspect import warnings from abc import ABCMeta, abstractmethod from mmcv_custom.fileio.zipreader import ZipReader class BaseStorageBackend(metaclass=ABCMeta): """Abstract class of storage backends. All backends need to implement two apis: `get()` and `get_text()`. `get()` reads the file as a byte ...
file_extension_for_content_type
Returns file extension for given content-type as an instance of a given type URI, or None. >>> file_extension_for_content_type(ANNAL.CURIE.Richtext, "text/markdown") == "md" True >>> file_extension_for_content_type(ANNAL.CURIE.Resource, "text/markdown") == "md" True >>> file_extension_for_content_type(ANNAL.CURIE.Reso...
# pylint: disable=no-member, redefined-outer-name """ Annalist resource types module """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2015, G. Klyne" __license__ = "MIT (http://o...
def file_extension_for_content_type(typeuri, content_type): """ Returns file extension for given content-type as an instance of a given type URI, or None. >>> file_extension_for_content_type(ANNAL.CURIE.Richtext, "text/markdown") == "md" True >>> file_extension_for_content_type(ANNAL.CURIE.Reso...
99
117
# pylint: disable=no-member, redefined-outer-name """ Annalist resource types module """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2015, G. Klyne" __license__ = "MIT (http://o...
content_type_for_file_extension
Returns content-type for given file extension as an instance of a given type URI, or None. >>> content_type_for_file_extension(ANNAL.CURIE.Richtext, "md") == "text/markdown" True >>> content_type_for_file_extension(ANNAL.CURIE.Resource, "md") == "text/markdown" True >>> content_type_for_file_extension(ANNAL.CURIE.Reso...
# pylint: disable=no-member, redefined-outer-name """ Annalist resource types module """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2015, G. Klyne" __license__ = "MIT (http://o...
def content_type_for_file_extension(typeuri, file_extension): """ Returns content-type for given file extension as an instance of a given type URI, or None. >>> content_type_for_file_extension(ANNAL.CURIE.Richtext, "md") == "text/markdown" True >>> content_type_for_file_extension(ANNAL.CURIE.Re...
119
137
# pylint: disable=no-member, redefined-outer-name """ Annalist resource types module """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2015, G. Klyne" __license__ = "MIT (http://o...
rotate
Rotate. Applies the rotation `matrix` to a set of particles positions `pos` and velocities `vel` Parameters ---------- pos : `np.ndarray`, shape = (N_part, 3) Positions of particles vel : `np.ndarray`, shape = (N_part, 3) Velocities of particles matrix : `np.ndarray` Rotation matrix, with shape (3, 3) Re...
# This file is part of # the galxy-chop project (https://github.com/vcristiani/galaxy-chop) # Copyright (c) 2020, Valeria Cristiani # License: MIT # Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt """Fixtures input data.""" # ===============================================================...
def rotate(pos, vel, matrix): """ Rotate. Applies the rotation `matrix` to a set of particles positions `pos` and velocities `vel` Parameters ---------- pos : `np.ndarray`, shape = (N_part, 3) Positions of particles vel : `np.ndarray`, shape = (N_part, 3) Velocities of ...
109
135
# This file is part of # the galxy-chop project (https://github.com/vcristiani/galaxy-chop) # Copyright (c) 2020, Valeria Cristiani # License: MIT # Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt """Fixtures input data.""" # ===============================================================...
distance
Distances calculator. Calculate distances beetween particles. Parameters ---------- x, y, z: `np.ndarray`, shape = (N_part, 1) Positions m : `np.ndarray`, shape = (N_part, 1) Masses Returns ------- dx, dy, dz: `np.ndarray`, shape = (N_part, N_part) Distances between particles.
# This file is part of # the galxy-chop project (https://github.com/vcristiani/galaxy-chop) # Copyright (c) 2020, Valeria Cristiani # License: MIT # Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt """Fixtures input data.""" # ===============================================================...
def distance(x, y, z, m): """ Distances calculator. Calculate distances beetween particles. Parameters ---------- x, y, z: `np.ndarray`, shape = (N_part, 1) Positions m : `np.ndarray`, shape = (N_part, 1) Masses Returns ------- dx, dy, dz: `np.ndarray`, shape =...
138
172
# This file is part of # the galxy-chop project (https://github.com/vcristiani/galaxy-chop) # Copyright (c) 2020, Valeria Cristiani # License: MIT # Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt """Fixtures input data.""" # ===============================================================...
epot
Potential energy with python. Parameters ---------- x, y, z: `np.ndarray`, shape = (N_part, 1) Positions m : `np.ndarray`, shape = (N_part, 1) Masses eps: `float` Softening radius Returns ------- Upot: `np.ndarray`, shape = (N_part, 1) Potential energy of particles
# This file is part of # the galxy-chop project (https://github.com/vcristiani/galaxy-chop) # Copyright (c) 2020, Valeria Cristiani # License: MIT # Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt """Fixtures input data.""" # ===============================================================...
def epot(x, y, z, m, eps=0.0): """ Potential energy with python. Parameters ---------- x, y, z: `np.ndarray`, shape = (N_part, 1) Positions m : `np.ndarray`, shape = (N_part, 1) Masses eps: `float` Softening radius Returns ------- Upot: `np.ndarray`, sha...
175
208
# This file is part of # the galxy-chop project (https://github.com/vcristiani/galaxy-chop) # Copyright (c) 2020, Valeria Cristiani # License: MIT # Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt """Fixtures input data.""" # ===============================================================...
timestep
Converts a given time to an integer time step. This function slightly shifts the time before dividing it by ``dt`` to make sure that multiples of ``dt`` do not end up in the preceding time step due to floating point issues. This function is used in the refractoriness calculation. .. versionadded:: 2.1.3 Parameters --...
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
def timestep(t, dt): ''' Converts a given time to an integer time step. This function slightly shifts the time before dividing it by ``dt`` to make sure that multiples of ``dt`` do not end up in the preceding time step due to floating point issues. This function is used in the refractoriness calcula...
657
687
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
__getitem__
Find an implementation for this function that can be used by the `CodeObject` given as `key`. Will find implementations registered for `key` itself (or one of its parents), or for the `CodeGenerator` class that `key` uses (or one of its parents). In all cases, implementations registered for the corresponding names qual...
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
def __getitem__(self, key): ''' Find an implementation for this function that can be used by the `CodeObject` given as `key`. Will find implementations registered for `key` itself (or one of its parents), or for the `CodeGenerator` class that `key` uses (or one of its parents...
303
351
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
add_numpy_implementation
Add a numpy implementation to a `Function`. Parameters ---------- function : `Function` The function description for which an implementation should be added. wrapped_func : callable The original function (that will be used for the numpy implementation) dependencies : list of `Function`, optional A list of ...
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
def add_numpy_implementation(self, wrapped_func, dependencies=None, discard_units=None, compiler_kwds=None): ''' Add a numpy implementation to a `Function`. Parameters ---------- function : `Function` The function description for ...
353
444
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
add_dynamic_implementation
Adds an "dynamic implementation" for this function. `code` and `namespace` arguments are expected to be callables that will be called in `Network.before_run` with the owner of the `CodeObject` as an argument. This allows to generate code that depends on details of the context it is run in, e.g. the ``dt`` of a clock.
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
def add_dynamic_implementation(self, target, code, namespace=None, dependencies=None, availability_check=None, name=None, compiler_kwds=None): ''' Adds an "dynamic implementation" for this function. `code` and `namespace` ...
456
476
from collections.abc import Mapping import inspect import types from typing import Callable import numpy as np import sympy from sympy.codegen import cfunctions as sympy_cfunctions from numpy.random import randn, rand from sympy import Function as sympy_Function from sympy import S import brian2.units.unitsafefunctio...
get_sentiment
Analyzing Sentiment in a String Args: text_content The text content to analyze
# Copyright 2020 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...
def get_sentiment(instances_content): """Analyzing Sentiment in a String Args: text_content The text content to analyze """ scores = [] client = language_v1.LanguageServiceClient() encoding_type = enums.EncodingType.UTF8 language = 'en' type_ = enums.Document.Type.PLAIN_TEXT ...
44
78
# Copyright 2020 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...
run
Executes Pipeline. :param args: :param pipeline_args: :return:
# Copyright 2020 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...
def run(args, pipeline_args=None): """Executes Pipeline. :param args: :param pipeline_args: :return: """ """Build and run the pipeline.""" # We use the save_main_session option because one or more DoFn's in this # workflow rely on global context (e.g., a module imported at module level)...
153
214
# Copyright 2020 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...
_get_break_loop_node
Returns the loop node that holds the break node in arguments. Args: break_node (astroid.Break): the break node of interest. Returns: astroid.For or astroid.While: the loop node holding the break node.
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
def _get_break_loop_node(break_node): """ Returns the loop node that holds the break node in arguments. Args: break_node (astroid.Break): the break node of interest. Returns: astroid.For or astroid.While: the loop node holding the break node. """ loop_nodes = (astroid.For, astr...
266
285
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
_loop_exits_early
Returns true if a loop may ends up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may ends up in a break statement, False otherwise.
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
def _loop_exits_early(loop): """ Returns true if a loop may ends up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may ends up in a break statement, False otherwise. """ loop_nodes = (astroid.For, astroid....
288
309
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
_get_properties
Returns a tuple of property classes and names. Property classes are fully qualified, such as 'abc.abstractproperty' and property names are the actual names, such as 'abstract_property'.
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
def _get_properties(config): """Returns a tuple of property classes and names. Property classes are fully qualified, such as 'abc.abstractproperty' and property names are the actual names, such as 'abstract_property'. """ property_classes = {BUILTIN_PROPERTY} property_names = set() # Not retur...
324
337
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
redefined_by_decorator
return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: ...
435
451
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
_check_not_in_finally
check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
def _check_not_in_finally(self, node, node_name, breaker_classes=()): """check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.""" # if self...
1,486
1,502
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
_check_logical_tautology
Check if identifier is compared against itself. :param node: Compare node :type node: astroid.node_classes.Compare :Example: val = 786 if val == val: # [comparison-with-itself] pass
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
def _check_logical_tautology(self, node): """Check if identifier is compared against itself. :param node: Compare node :type node: astroid.node_classes.Compare :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_ope...
2,490
2,515
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2010 Daniel Harding <dharding@gmail.com> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persau...
__init__
For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based...
""" A helper class for using TLS Lite with stdlib clients (httplib, xmlrpclib, imaplib, poplib). """ from tlslite.Checker import Checker class ClientHelper: """This is a helper class used to integrate TLS Lite with various TLS clients (e.g. poplib, smtplib, httplib, etc.)""" # MASKED: __init__ function (line...
def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): """ For...
12
144
""" A helper class for using TLS Lite with stdlib clients (httplib, xmlrpclib, imaplib, poplib). """ from tlslite.Checker import Checker class ClientHelper: """This is a helper class used to integrate TLS Lite with various TLS clients (e.g. poplib, smtplib, httplib, etc.)""" def __init__(self, ...
spline_filter1d
Calculates a one-dimensional spline filter along the given axis. The lines of the array along the given axis are filtered by a spline filter. The order of the spline must be >= 2 and <= 5.
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def spline_filter1d(input, order = 3, axis = -1, output = numpy.float64, output_type = None): """Calculates a one-dimensional spline filter along the given axis. The lines of the array along the given axis are filtered by a spline filter. The order of the spline must be >= 2 and <= 5. ...
40
59
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
spline_filter
Multi-dimensional spline filter. Note: The multi-dimensional filter is implemented as a sequence of one-dimensional spline filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may...
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def spline_filter(input, order = 3, output = numpy.float64, output_type = None): """Multi-dimensional spline filter. Note: The multi-dimensional filter is implemented as a sequence of one-dimensional spline filters. The intermediate arrays are stored in the same data type as the outpu...
62
85
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
geometric_transform
Apply an arbritrary geometric transform. The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order. mapping must be a callable object that accepts a tupl...
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def geometric_transform(input, mapping, output_shape = None, output_type = None, output = None, order = 3, mode = 'constant', cval = 0.0, prefilter = True, extra_arguments = (), extra_keywords = {}): """Apply an arbritrary geometric transform. ...
87
141
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
affine_transform
Apply an affine transformation. The given matrix and offset are used to find for each point in the output the corresponding coordinates in the input by an affine transformation. The value of the input at those coordinates is determined by spline interpolation of the requested order. Points outside the boundaries of th...
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def affine_transform(input, matrix, offset = 0.0, output_shape = None, output_type = None, output = None, order = 3, mode = 'constant', cval = 0.0, prefilter = True): """Apply an affine transformation. The given matrix and offset are used to find for each point in the ...
248
305
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
shift
Shift an array. The array is shifted using spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode. The parameter prefilter determines if the input is pre-filtered before interpolation, if False it is assumed that the input is already filtered.
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def shift(input, shift, output_type = None, output = None, order = 3, mode = 'constant', cval = 0.0, prefilter = True): """Shift an array. The array is shifted using spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode....
308
338
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
zoom
Zoom an array. The array is zoomed using spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode. The parameter prefilter determines if the input is pre- filtered before interpolation, if False it is assumed that the input is already filtered.
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def zoom(input, zoom, output_type = None, output = None, order = 3, mode = 'constant', cval = 0.0, prefilter = True): """Zoom an array. The array is zoomed using spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode. The ...
341
371
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
make_request
Make a web request using the given method and path, feed it the content, and return the Request and the Channel underneath. Args: method (bytes/unicode): The HTTP request method ("verb"). path (bytes/unicode): The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces and such). content (bytes or...
import json from io import BytesIO from six import text_type import attr from zope.interface import implementer from twisted.internet import address, threads, udp from twisted.internet._resolver import HostResolution from twisted.internet.address import IPv4Address from twisted.internet.defer import Deferred from tw...
def make_request( reactor, method, path, content=b"", access_token=None, request=SynapseRequest, shorthand=True, ): """ Make a web request using the given method and path, feed it the content, and return the Request and the Channel underneath. Args: method (bytes/uni...
119
175
import json from io import BytesIO from six import text_type import attr from zope.interface import implementer from twisted.internet import address, threads, udp from twisted.internet._resolver import HostResolution from twisted.internet.address import IPv4Address from twisted.internet.defer import Deferred from tw...
get_all_concentrations
Get all entries that have concentration values Args: projection (dict, optional): mongodb query projection. Defaults to {'_id': 0, 'inchi': 1,'inchikey': 1, 'smiles': 1, 'name': 1}. Returns: (list): all results that meet the constraint.
from datanator_query_python.util import mongo_util from pymongo.collation import Collation, CollationStrength class QueryXmdb: def __init__(self, username=None, password=None, server=None, authSource='admin', database='datanator', max_entries=float('inf'), verbose=True, collection_str='ecmdb', ...
def get_all_concentrations(self, projection={'_id': 0, 'inchi': 1, 'inchikey': 1, 'smiles': 1, 'name': 1}): """Get all entries that have concentration values Args: projection (dict, optional): mongodb query projection. Defaults to {'_id': 0, 'inchi'...
19
34
from datanator_query_python.util import mongo_util from pymongo.collation import Collation, CollationStrength class QueryXmdb: def __init__(self, username=None, password=None, server=None, authSource='admin', database='datanator', max_entries=float('inf'), verbose=True, collection_str='ecmdb', ...
get_name_by_inchikey
Get metabolite's name by its inchikey Args: inchikey (:obj:`str`): inchi key of metabolite Return: (:obj:`str`): name of metabolite
from datanator_query_python.util import mongo_util from pymongo.collation import Collation, CollationStrength class QueryXmdb: def __init__(self, username=None, password=None, server=None, authSource='admin', database='datanator', max_entries=float('inf'), verbose=True, collection_str='ecmdb', ...
def get_name_by_inchikey(self, inchikey): """Get metabolite's name by its inchikey Args: inchikey (:obj:`str`): inchi key of metabolite Return: (:obj:`str`): name of metabolite """ query = {'inchikey': inchikey} projection = {'_id': 0...
36
51
from datanator_query_python.util import mongo_util from pymongo.collation import Collation, CollationStrength class QueryXmdb: def __init__(self, username=None, password=None, server=None, authSource='admin', database='datanator', max_entries=float('inf'), verbose=True, collection_str='ecmdb', ...
__call__
Args: dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format. Returns: dict: a format that builtin models in detectron2 accept
# Copyright (c) Facebook, Inc. and its affiliates. import copy import logging import numpy as np from typing import List, Optional, Union import torch from detectron2.config import configurable from . import detection_utils as utils from . import transforms as T """ This file contains the default mapping that's appl...
def __call__(self, dataset_dict): """ Args: dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format. Returns: dict: a format that builtin models in detectron2 accept """ dataset_dict = copy.deepcopy(dataset_dict) # it will be modifie...
115
187
# Copyright (c) Facebook, Inc. and its affiliates. import copy import logging import numpy as np from typing import List, Optional, Union import torch from detectron2.config import configurable from . import detection_utils as utils from . import transforms as T """ This file contains the default mapping that's appl...
shift_decoder
Shifts the indices of a decoder by a constant. Args: decoder (iterable): list of BinaryPolynomial; the decoder shift_constant (int): the qubit index that corresponds to the offset. Returns (list): list of BinaryPolynomial shifted decoder
# 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, software # distribu...
def shift_decoder(decoder, shift_constant): """ Shifts the indices of a decoder by a constant. Args: decoder (iterable): list of BinaryPolynomial; the decoder shift_constant (int): the qubit index that corresponds to the offset. Returns (list): list of BinaryPolynomial shifted decoder ...
24
42
# 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, software # distribu...
double_decoding
Concatenates two decodings Args: decoder_1 (iterable): list of BinaryPolynomial decoding of the outer code layer decoder_2 (iterable): list of BinaryPolynomial decoding of the inner code layer Returns (list): list of BinaryPolynomial the decoding defined by w -> decoder_1( decoder_2(w) )
# 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, software # distribu...
def double_decoding(decoder_1, decoder_2): """ Concatenates two decodings Args: decoder_1 (iterable): list of BinaryPolynomial decoding of the outer code layer decoder_2 (iterable): list of BinaryPolynomial decoding of the inner code layer Returns (list): list of Bi...
45
67
# 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, software # distribu...
__init__
Initialization of a binary code. Args: encoding (np.ndarray or list): nested lists or binary 2D-array decoding (array or list): list of BinaryPolynomial (list or str). Raises: TypeError: non-list, array like encoding or decoding, unsuitable BinaryPolynomial generators, BinaryCodeError: in case...
# 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, software # distribu...
def __init__(self, encoding, decoding): """ Initialization of a binary code. Args: encoding (np.ndarray or list): nested lists or binary 2D-array decoding (array or list): list of BinaryPolynomial (list or str). Raises: TypeError: non-list, array like en...
129
179
# 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, software # distribu...
__iadd__
In-place appending a binary code with +=. Args: appendix (BinaryCode): The code to append to the present one. Returns (BinaryCode): A global binary code with size (n_modes1 + n_modes2), (n_qubits1,n_qubits2) Raises: TypeError: Appendix must be a BinaryCode.
# 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, software # distribu...
def __iadd__(self, appendix): """ In-place appending a binary code with +=. Args: appendix (BinaryCode): The code to append to the present one. Returns (BinaryCode): A global binary code with size (n_modes1 + n_modes2), (n_qubits1,n_qubits2) Raises: ...
181
202
# 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, software # distribu...
__add__
Appends two binary codes via addition +. Args: appendix (BinaryCode): The code to append to the present one. Returns (BinaryCode): global binary code
# 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, software # distribu...
def __add__(self, appendix): """Appends two binary codes via addition +. Args: appendix (BinaryCode): The code to append to the present one. Returns (BinaryCode): global binary code """ twin = copy.deepcopy(self) twin += appendix return twin
204
214
# 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, software # distribu...
__imul__
In-place code concatenation or appendage via *= . Multiplication with integer will yield appendage, otherwise concatenation. Args: factor (int or BinaryCode): the BinaryCode to concatenate. In case of int, it will append the code to itself factor times. Returns (BinaryCode): segmented or concatenated code...
# 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, software # distribu...
def __imul__(self, factor): """In-place code concatenation or appendage via *= . Multiplication with integer will yield appendage, otherwise concatenation. Args: factor (int or BinaryCode): the BinaryCode to concatenate. In case of int, it will append the...
216
261
# 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, software # distribu...
__mul__
Concatenation of two codes or appendage the same code factor times in case of integer factor. Args: factor (int or BinaryCode): the BinaryCode to concatenate. In case of int, it will append the code to itself factor times. Returns (BinaryCode): segmented or concatenated code
# 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, software # distribu...
def __mul__(self, factor): """ Concatenation of two codes or appendage the same code factor times in case of integer factor. Args: factor (int or BinaryCode): the BinaryCode to concatenate. In case of int, it will append the code to itself factor times. ...
263
275
# 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, software # distribu...
feedback
Stores the feedback for a recommended post. Will return a information object on success and an empty object on failure. Think about returning 409-Conflict on failure instead, because the empty object can cause an issue in engine service.
from concurrent.futures import ThreadPoolExecutor, CancelledError from aiomysql import create_pool from asyncio import ensure_future, gather, sleep from pymysql.err import OperationalError from logging import getLogger from sanic import Sanic from sanic.request import Request from sanic.response import json from sanic....
@app.post('/feedback') async def feedback(request: Request): '''Stores the feedback for a recommended post. Will return a information object on success and an empty object on failure. Think about returning 409-Conflict on failure instead, because the empty object can cause an issue in engine service.''' vot...
106
119
from concurrent.futures import ThreadPoolExecutor, CancelledError from aiomysql import create_pool from asyncio import ensure_future, gather, sleep from pymysql.err import OperationalError from logging import getLogger from sanic import Sanic from sanic.request import Request from sanic.response import json from sanic....
allocate_buffers
Allocates host and device buffer for TRT engine inference. This function is similair to the one in ../../common.py, but converts network outputs (which are np.float32) appropriately before writing them to Python buffer. This is needed, since TensorRT plugins doesn't support output type description, and in our particul...
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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...
def allocate_buffers(engine): """Allocates host and device buffer for TRT engine inference. This function is similair to the one in ../../common.py, but converts network outputs (which are np.float32) appropriately before writing them to Python buffer. This is needed, since TensorRT plugins doesn't...
39
81
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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...
rainbow_to_vector
Convert Rainbow object to np.arrays Parameters ---------- r : Rainbow object chromatic Rainbow object to convert into array format timeformat : str (optional, default='hours') The time format to use (seconds, minutes, hours, days etc.) Returns ---------- rflux : np.array flux...
from .imports import * # MASKED: rainbow_to_vector function (lines 4-51) def rainbow_to_df(r, timeformat='h'): """ Convert Rainbow object to pandas dataframe Parameters ---------- r : Rainbow object chromatic Rainbow object to convert into pandas df format timeformat : str ...
def rainbow_to_vector(r, timeformat='h'): """ Convert Rainbow object to np.arrays Parameters ---------- r : Rainbow object chromatic Rainbow object to convert into array format timeformat : str (optional, default='hours') The time format to use (seconds, m...
4
51
from .imports import * def rainbow_to_vector(r, timeformat='h'): """ Convert Rainbow object to np.arrays Parameters ---------- r : Rainbow object chromatic Rainbow object to convert into array format timeformat : str (optional, default='hours') The time ...
train_step
train_step() API for module wrapped by DistributedDataParallel. This method is basically the same as ``DistributedDataParallel.forward()``, while replacing ``self.module.forward()`` with ``self.module.train_step()``. It is compatible with PyTorch 1.1 - 1.5.
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel.distributed import (DistributedDataParallel, _find_tensors) from mmcv import print_log from mmcv.utils import TORCH_VERSION, digit_version from .scatter_gather import scatter_kwargs class MM...
def train_step(self, *inputs, **kwargs): """train_step() API for module wrapped by DistributedDataParallel. This method is basically the same as ``DistributedDataParallel.forward()``, while replacing ``self.module.forward()`` with ``self.module.train_step()``. It is compatib...
29
83
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel.distributed import (DistributedDataParallel, _find_tensors) from mmcv import print_log from mmcv.utils import TORCH_VERSION, digit_version from .scatter_gather import scatter_kwargs class MM...
val_step
val_step() API for module wrapped by DistributedDataParallel. This method is basically the same as ``DistributedDataParallel.forward()``, while replacing ``self.module.forward()`` with ``self.module.val_step()``. It is compatible with PyTorch 1.1 - 1.5.
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel.distributed import (DistributedDataParallel, _find_tensors) from mmcv import print_log from mmcv.utils import TORCH_VERSION, digit_version from .scatter_gather import scatter_kwargs class MM...
def val_step(self, *inputs, **kwargs): """val_step() API for module wrapped by DistributedDataParallel. This method is basically the same as ``DistributedDataParallel.forward()``, while replacing ``self.module.forward()`` with ``self.module.val_step()``. It is compatible wit...
85
138
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel.distributed import (DistributedDataParallel, _find_tensors) from mmcv import print_log from mmcv.utils import TORCH_VERSION, digit_version from .scatter_gather import scatter_kwargs class MM...
request
Send an HTTP request :param method: HTTP request method, as an all caps string :type method: str :param path: Path for the request, with or without leading slash :type path: str :param query_params: Parameters to be encoded as a query string :type query_params: dict, optional :param headers: HTTP headers to add to the...
import logging import urllib.parse from typing import Any, Dict, Optional, Type, Union from globus_sdk import config, exc, utils from globus_sdk.authorizers import GlobusAuthorizer from globus_sdk.paging import PaginatorTable from globus_sdk.response import GlobusHTTPResponse from globus_sdk.scopes import ScopeBuilder...
def request( self, method: str, path: str, *, query_params: Optional[Dict[str, Any]] = None, data: Union[None, Dict[str, Any], utils.PayloadWrapper] = None, headers: Optional[Dict[str, str]] = None, encoding: Optional[str] = None, ) -> GlobusHTTPRe...
237
298
import logging import urllib.parse from typing import Any, Dict, Optional, Type, Union from globus_sdk import config, exc, utils from globus_sdk.authorizers import GlobusAuthorizer from globus_sdk.paging import PaginatorTable from globus_sdk.response import GlobusHTTPResponse from globus_sdk.scopes import ScopeBuilder...
build_stats
Normalizes and returns dictionary of stats. Args: history: Results of the training step. Supports both categorical_accuracy and sparse_categorical_accuracy. eval_output: Output of the eval step. Assumes first value is eval_loss and second value is accuracy_top_1. callbacks: a list of callbacks which migh...
# 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 build_stats(history, eval_output, callbacks): """Normalizes and returns dictionary of stats. Args: history: Results of the training step. Supports both categorical_accuracy and sparse_categorical_accuracy. eval_output: Output of the eval step. Assumes first value is eval_loss and second val...
230
273
# 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...
get_synth_data
Creates a set of synthetic random data. Args: height: Integer height that will be used to create a fake image tensor. width: Integer width that will be used to create a fake image tensor. num_channels: Integer depth that will be used to create a fake image tensor. num_classes: Number of classes that should be ...
# 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 get_synth_data(height, width, num_channels, num_classes, dtype): """Creates a set of synthetic random data. Args: height: Integer height that will be used to create a fake image tensor. width: Integer width that will be used to create a fake image tensor. num_channels: Integer depth that will be us...
387
413
# 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...
get_gkey
Retrieve a requested global keyword The method searches the list of global keywords for a fitting keyword. In case that the requested keyword exists, it is returned. If not 'None' is returned Parameters ---------- keyword: str name of the requested keyword Returns ------- key: str or None the requested keywo...
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
def get_gkey(self, keyword): """Retrieve a requested global keyword The method searches the list of global keywords for a fitting keyword. In case that the requested keyword exists, it is returned. If not 'None' is returned Parameters ---------- keyw...
328
358
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
add_gkey
Add global keyword The method adds a keyword to the list of global keywords. In case that the keyword just exists, it is overwritten, otherwise it is appended to the global keyword list. Parameters ---------- keyword: str name of the requested keyword keyvalue: any value of the requested keyword comment: str ...
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
def add_gkey(self, keyword, keyvalue, comment=None): """Add global keyword The method adds a keyword to the list of global keywords. In case that the keyword just exists, it is overwritten, otherwise it is appended to the global keyword list. Parameters ----...
360
387
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
get_gvalue
Retrieve a requested global keyword value The method returns the value of the keyword which matches the requested value. If there is no matching keyword, 'None' is returned. Parameters ---------- keyword: str name of the requested keyword Returns ------- The keyword value
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
def get_gvalue(self, keyword): """Retrieve a requested global keyword value The method returns the value of the keyword which matches the requested value. If there is no matching keyword, 'None' is returned. Parameters ---------- keyword: str ...
454
484
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
get_bkey
Retrieve a requested beam keyword The method searches the list of beam keywords for a fitting keyword. In case that the requested keyword exists, it is returned. If not 'None' is returned Parameters ---------- keyword: str name of the requested keyword Returns ------- key: str or None the requested keyword o...
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
def get_bkey(self, keyword): """Retrieve a requested beam keyword The method searches the list of beam keywords for a fitting keyword. In case that the requested keyword exists, it is returned. If not 'None' is returned Parameters ---------- keyword:...
867
897
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
get_bvalue
Retrieve a requested beam-keyword value The method returns the value of the keyword which matches the requested value. If there is no matching keyword, 'None' is returned. Parameters ---------- keyword: str name of the requested keyword Returns ------- key: str or None the requested keyword or 'None'
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
def get_bvalue(self, keyword): """Retrieve a requested beam-keyword value The method returns the value of the keyword which matches the requested value. If there is no matching keyword, 'None' is returned. Parameters ---------- keyword: str ...
899
929
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
__init__
Constructor for the keyword list class Initializer for the keyword list class. The keyword instance is created using all input values. Parameters ---------- keyword: str the keword name keyvalue: str the keyword values comment: str the keyword comment
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
def __init__(self, keyword, keyvalue, comment=None): """Constructor for the keyword list class Initializer for the keyword list class. The keyword instance is created using all input values. Parameters ---------- keyword: str the keword name ...
1,451
1,477
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
fetch_filenames
subject_list : list of short subject IDs in string format file_type : must be one of the available file types returns: filenames : list of filetypes (same length as subject_list)
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def fetch_filenames(subject_list, file_type): """ subject_list : list of short subject IDs in string format file_type : must be one of the available file types returns: filenames : list of filetypes (same length as subject_list) """ # Specify file mappings for the possib...
62
100
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
fetch_subject_files
subjectID : short subject ID for which list of available files are fetched returns: onlyfiles : list of absolute paths for available subject files
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def fetch_subject_files(subjectID): """ subjectID : short subject ID for which list of available files are fetched returns: onlyfiles : list of absolute paths for available subject files """ # Load subject ID lists subject_IDs = get_ids(short=True) subject_IDs = subject_IDs.to...
103
125
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
fetch_conn_matrices
subject_list : list of short subject IDs in string format atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200 kind : the kind of correlation used to estimate the matrices, i.e. returns: connectivity : list of square connectivity matrices, one for each subject in...
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def fetch_conn_matrices(subject_list, atlas_name, kind): """ subject_list : list of short subject IDs in string format atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200 kind : the kind of correlation used to estimate the matrices, i.e. returns:...
128
151
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
get_timeseries
subject_list : list of short subject IDs in string format atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200 returns: ts : list of timeseries arrays, each of shape (timepoints x regions)
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def get_timeseries(subject_list, atlas_name): """ subject_list : list of short subject IDs in string format atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200 returns: ts : list of timeseries arrays, each of shape (timepoints x regions) ""...
154
171
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
norm_timeseries
ts_list : list of timeseries arrays, each of shape (timepoints x regions) returns: norm_ts : list of normalised timeseries arrays, same shape as ts_list
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def norm_timeseries(ts_list): """ ts_list : list of timeseries arrays, each of shape (timepoints x regions) returns: norm_ts : list of normalised timeseries arrays, same shape as ts_list """ norm_ts = [] for ts in ts_list: norm_ts.append(nilearn.signal.clean(ts, detr...
174
187
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
get_subject_label
subject_list : the subject short IDs list label_name : name of the label to be retrieved returns: label : dictionary of subject labels
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def get_subject_label(subject_list, label_name): """ subject_list : the subject short IDs list label_name : name of the label to be retrieved returns: label : dictionary of subject labels """ label = {} with open(os.path.join(save_path, 'ABIDE_pcp/Phenotypic_V1_0b...
262
280
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
load_all_networks
subject_list : the subject short IDs list kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation atlas_name : name of the atlas used returns: all_networks : list of connectivity matrices (regions x regions)
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def load_all_networks(subject_list, kind, atlas_name="aal"): """ subject_list : the subject short IDs list kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation atlas_name : name of the atlas used returns: all_networks : list of conne...
283
307
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
get_net_vectors
subject_list : the subject short IDs list kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation atlas_name : name of the atlas used returns: matrix : matrix of connectivity vectors (num_subjects x num_connections)
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def get_net_vectors(subject_list, kind, atlas_name="aal"): """ subject_list : the subject short IDs list kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation atlas_name : name of the atlas used returns: matrix : matrix of conne...
310
331
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
get_atlas_coords
atlas_name : name of the atlas used returns: matrix : matrix of roi 3D coordinates in MNI space (num_rois x 3)
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def get_atlas_coords(atlas_name='ho'): """ atlas_name : name of the atlas used returns: matrix : matrix of roi 3D coordinates in MNI space (num_rois x 3) """ coords_file = os.path.join(root_folder, atlas_name + '_coords.csv') coords = np.loadtxt(coords_file, delimiter=',') ...
334
348
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
_CheckIamPermissions
Check for needed IAM permissions and prompt to add if missing. Args: project_id: A string with the name of the project.
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
def _CheckIamPermissions(project_id): """Check for needed IAM permissions and prompt to add if missing. Args: project_id: A string with the name of the project. """ project = projects_api.Get(project_id) # If the user's project doesn't have cloudbuild enabled yet, then the service # account won't even ...
180
232
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
_CreateCloudBuild
Create a build in cloud build. Args: build_config: A cloud build Build message. client: The cloud build api client. messages: The cloud build api messages module. Returns: Tuple containing a cloud build build object and the resource reference for that build.
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
def _CreateCloudBuild(build_config, client, messages): """Create a build in cloud build. Args: build_config: A cloud build Build message. client: The cloud build api client. messages: The cloud build api messages module. Returns: Tuple containing a cloud build build object and the resource refer...
235
266
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
GetDaisyBucketName
Determine bucket name for daisy. Args: bucket_location: str, specified bucket location. Returns: str, bucket name for daisy.
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
def GetDaisyBucketName(bucket_location=None): """Determine bucket name for daisy. Args: bucket_location: str, specified bucket location. Returns: str, bucket name for daisy. """ project = properties.VALUES.core.project.GetOrFail() safe_project = project.replace(':', '-') safe_project = safe_proj...
269
287
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
AppendNetworkAndSubnetArgs
Extracts network/subnet out of CLI args and append for importer. Args: args: list of str, CLI args that might contain network/subnet args. builder_args: list of str, args for builder.
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
def AppendNetworkAndSubnetArgs(args, builder_args): """Extracts network/subnet out of CLI args and append for importer. Args: args: list of str, CLI args that might contain network/subnet args. builder_args: list of str, args for builder. """ if args.subnet: AppendArg(builder_args, 'subnet', args.s...
318
329
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
MakeGcsObjectOrPathUri
Creates Google Cloud Storage URI for an object or a path. Raises storage_util.InvalidObjectNameError if a path contains only bucket name. Args: uri: a string to a Google Cloud Storage object or a path. Can be a gs:// or an https:// variant. Returns: Google Cloud Storage URI for an object or a path.
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
def MakeGcsObjectOrPathUri(uri): """Creates Google Cloud Storage URI for an object or a path. Raises storage_util.InvalidObjectNameError if a path contains only bucket name. Args: uri: a string to a Google Cloud Storage object or a path. Can be a gs:// or an https:// variant. Returns: Goog...
621
638
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
StreamWithFilter
Stream the logs for a build using whitelist filter. Args: build_ref: Build reference, The build whose logs shall be streamed. backoff: A function that takes the current elapsed time and returns the next sleep length. Both are in seconds. output_filter: List of strings, The output will only be shown if the li...
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
def StreamWithFilter(self, build_ref, backoff, output_filter=None): """Stream the logs for a build using whitelist filter. Args: build_ref: Build reference, The build whose logs shall be streamed. backoff: A function that takes the current elapsed time and returns the next sleep length. B...
76
119
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
setup_wandb
Setup the optional Weights & Biases (`wandb`) integration. One can subclass and override this method to customize the setup if needed. Find more information `here <https://docs.wandb.com/huggingface>`__. You can also override the following environment variables: Environment: WANDB_PROJECT: (Optional): str...
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
def setup_wandb(self): """ Setup the optional Weights & Biases (`wandb`) integration. One can subclass and override this method to customize the setup if needed. Find more information `here <https://docs.wandb.com/huggingface>`__. You can also override the following environment vari...
233
255
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
setup_comet
Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments COMET_OFFLINE_DIRECTORY: (Optional): str - folder to use for saving offline experiments ...
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
def setup_comet(self): """ Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments C...
257
285
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
prediction_loop
Prediction/evaluation loop, shared by :func:`~transformers.TFTrainer.evaluate` and :func:`~transformers.TFTrainer.predict`. Works both with or without labels.
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
def prediction_loop( self, dataset: tf.data.Dataset, steps: int, num_examples: int, description: str, prediction_loss_only: Optional[bool] = None, ) -> PredictionOutput: """ Prediction/evaluation loop, shared by :func:`~transformers.TFTrainer.evalu...
287
378
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
log
Log :obj:`logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (:obj:`Dict[str, float]`): The values to log.
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
def log(self, logs: Dict[str, float]) -> None: """ Log :obj:`logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (:obj:`Dict[str, float]`): The values to log. """ if hasa...
380
416
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
run_model
Computes the loss of the given features and labels pair. Subclass and override this method if you want to inject some custom behavior. Args: features (:obj:`tf.Tensor`): A batch of input features. labels (:obj:`tf.Tensor`): A batch of labels. training (:obj:`bool`): Whether or not to run the model in trai...
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
def run_model(self, features, labels, training): """ Computes the loss of the given features and labels pair. Subclass and override this method if you want to inject some custom behavior. Args: features (:obj:`tf.Tensor`): A batch of input features. labels (...
716
750
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
__init__
:param Attacker attacker: The attacker you use. :param Classifier classifier: The classifier you want to attack. :param int invoke_limit: Limitation of invoke for each instance. :param bool average_invoke: If true, returns "Avg. Victim Model Queries". :param kwargs: Other parameters, see :py:class:`.DefaultAttackEval` ...
from .default import DefaultAttackEval from ..classifier import Classifier from ..attacker import Attacker import json from tqdm import tqdm class InvokeLimitException(Exception): pass class InvokeLimitClassifierWrapper(Classifier): def __init__(self, clsf, invoke_limit): self.__invoke_limit = invoke_...
def __init__(self, attacker, classifier, invoke_limit=100, average_invoke=False, **kwargs): """ :param Attacker attacker: The attacker you use. :param Classifier classifier: The classifier you want to attack. :param int invoke_limit: Limitation of invoke for each ...
69
88
from .default import DefaultAttackEval from ..classifier import Classifier from ..attacker import Attacker import json from tqdm import tqdm class InvokeLimitException(Exception): pass class InvokeLimitClassifierWrapper(Classifier): def __init__(self, clsf, invoke_limit): self.__invoke_limit = invoke_...
_compute_inverse_bounds
Computes the image of the transform so we can clip when we untransform. The inverse of the Yeo-Johnson transform is given by: if X >= 0 and lambda == 0: X = exp(X_trans) - 1 elif X >= 0 and lambda != 0: X = (X_trans * lambda + 1) ** (1 / lambda) - 1 elif X < 0 and lambda != 2: X = 1 - (-(2 - lambda) * X_tr...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from collections import defaultdict from typing import TYPE_CHECKING, Dict, List,...
def _compute_inverse_bounds( power_transforms: Dict[str, PowerTransformer], tol: float = 1e-10 ) -> Dict[str, Tuple[float, float]]: """Computes the image of the transform so we can clip when we untransform. The inverse of the Yeo-Johnson transform is given by: if X >= 0 and lambda == 0: X = exp...
153
186
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from collections import defaultdict from typing import TYPE_CHECKING, Dict, List,...
write
Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
# # Copyright 2019 Jonas Berg # # 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...
def write(self, inputdata): """Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Py...
146
181
# # Copyright 2019 Jonas Berg # # 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...