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
test_set_one_ca_list
If passed a list containing a single X509Name, `Context.set_client_ca_list` configures the context to send that CA name to the client and, on both the server and client sides, `Connection.get_client_ca_list` returns a list containing that X509Name after the connection is set up.
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
def test_set_one_ca_list(self): """ If passed a list containing a single X509Name, `Context.set_client_ca_list` configures the context to send that CA name to the client and, on both the server and client sides, `Connection.get_client_ca_list` returns a list containing that ...
3,514
3,528
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
test_set_multiple_ca_list
If passed a list containing multiple X509Name objects, `Context.set_client_ca_list` configures the context to send those CA names to the client and, on both the server and client sides, `Connection.get_client_ca_list` returns a list containing those X509Names after the connection is set up.
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
def test_set_multiple_ca_list(self): """ If passed a list containing multiple X509Name objects, `Context.set_client_ca_list` configures the context to send those CA names to the client and, on both the server and client sides, `Connection.get_client_ca_list` returns a list co...
3,530
3,548
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
test_set_after_add_client_ca
A call to `Context.set_client_ca_list` after a call to `Context.add_client_ca` replaces the CA name specified by the former call with the names specified by the latter call.
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
def test_set_after_add_client_ca(self): """ A call to `Context.set_client_ca_list` after a call to `Context.add_client_ca` replaces the CA name specified by the former call with the names specified by the latter call. """ cacert = load_certificate(FILETYPE_PEM, root_c...
3,648
3,666
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
test_integers
All of the info constants are integers. This is a very weak test. It would be nice to have one that actually verifies that as certain info events happen, the value passed to the info callback matches up with the constant exposed by OpenSSL.SSL.
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
def test_integers(self): """ All of the info constants are integers. This is a very weak test. It would be nice to have one that actually verifies that as certain info events happen, the value passed to the info callback matches up with the constant exposed by OpenSSL.SSL. ...
3,673
3,694
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
_client_connection
Builds a client connection suitable for using OCSP. :param callback: The callback to register for OCSP. :param data: The opaque data object that will be handed to the OCSP callback. :param request_ocsp: Whether the client will actually ask for OCSP stapling. Useful for testing only.
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
def _client_connection(self, callback, data, request_ocsp=True): """ Builds a client connection suitable for using OCSP. :param callback: The callback to register for OCSP. :param data: The opaque data object that will be handed to the OCSP callback. :param reque...
3,741
3,759
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
_server_connection
Builds a server connection suitable for using OCSP. :param callback: The callback to register for OCSP. :param data: The opaque data object that will be handed to the OCSP callback.
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
def _server_connection(self, callback, data): """ Builds a server connection suitable for using OCSP. :param callback: The callback to register for OCSP. :param data: The opaque data object that will be handed to the OCSP callback. """ ctx = Context(SSLv2...
3,761
3,775
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
_GenerateCategories
Generates category string for each of the specified apps. Args: apps: list of tuples containing information about the apps. Returns: String containing concatenated copies of the category string for each app in apps, each populated with the appropriate app-specific strings.
# Copyright 2015 Google Inc. # # 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 _GenerateCategories(apps): """Generates category string for each of the specified apps. Args: apps: list of tuples containing information about the apps. Returns: String containing concatenated copies of the category string for each app in apps, each populated with the appropriate ...
385
409
# Copyright 2015 Google Inc. # # 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,...
_GeneratePolicies
Generates policy string for each of the specified apps. Args: apps: list of tuples containing information about the apps. Returns: String containing concatenated copies of the policy template for each app in apps, each populated with the appropriate app-specific strings.
# Copyright 2015 Google Inc. # # 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 _GeneratePolicies(apps): """Generates policy string for each of the specified apps. Args: apps: list of tuples containing information about the apps. Returns: String containing concatenated copies of the policy template for each app in apps, each populated with the appropriate app-...
411
434
# Copyright 2015 Google Inc. # # 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,...
GetLoss
Compute loss and also deriv w.r.t to it if asked for. Compute the loss function. Targets should be in self.data, predictions should be in self.state. Args: get_deriv: If True, compute the derivative w.r.t the loss function and put it in self.deriv.
from layer import * class LogisticLayer(Layer): def __init__(self, *args, **kwargs): super(LogisticLayer, self).__init__(*args, **kwargs) @classmethod def IsLayerType(cls, proto): return proto.hyperparams.activation == deepnet_pb2.Hyperparams.LOGISTIC def ApplyActivation(self): cm.sigmoid(self.st...
def GetLoss(self, get_deriv=False, acc_deriv=False, **kwargs): """Compute loss and also deriv w.r.t to it if asked for. Compute the loss function. Targets should be in self.data, predictions should be in self.state. Args: get_deriv: If True, compute the derivative w.r.t the loss function and pu...
21
62
from layer import * class LogisticLayer(Layer): def __init__(self, *args, **kwargs): super(LogisticLayer, self).__init__(*args, **kwargs) @classmethod def IsLayerType(cls, proto): return proto.hyperparams.activation == deepnet_pb2.Hyperparams.LOGISTIC def ApplyActivation(self): cm.sigmoid(self.st...
__str__
[summary] BoxWindow: :math:`[a_1, b_1] imes [a_2, b_2] imes \cdots` Returns: [str]: [description of the Box's bounds]
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def __str__(self): """[summary] BoxWindow: :math:`[a_1, b_1] \times [a_2, b_2] \times \cdots` Returns: [str]: [description of the Box's bounds] """ shape = (self.bounds).shape representation = "BoxWindow: " # * consider for a, b in self.bounds # ...
18
49
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
__contains__
[summary]This method tests if an element (args) is inside the box Args: args ([numpy array list]): [the element to test] Returns: [bool]: [True if the element is inside the box , False if not]
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def __contains__(self, args): """[summary]This method tests if an element (args) is inside the box Args: args ([numpy array list]): [the element to test] Returns: [bool]: [True if the element is inside the box , False if not] """ # * consider for (a,...
59
77
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
center
[summary] determinate the center of the box Returns: [numpy array list]: [the center of the box]
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def center(self): """[summary] determinate the center of the box Returns: [numpy array list]: [the center of the box] """ # * Nice try! # ? how about np.mean(self.bounds) c = np.zeros(self.__len__()) for i in range(self.__len__()): c[i...
115
126
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
rand
[summary] Generate ``n`` points uniformly at random inside the :py:class:`BoxWindow`. Args: n (int, optional): [description]. Defaults to 1. rng ([type], optional): [description]. Defaults to None. Returns: Randomly n elements that belong to the box
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def rand(self, n=1, rng=None): """[summary] Generate ``n`` points uniformly at random inside the :py:class:`BoxWindow`. Args: n (int, optional): [description]. Defaults to 1. rng ([type], optional): [description]. Defaults to None. Returns: Rando...
128
149
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
__init__
[summary]Initialization of Box's parameters Args: args ([numpy array list]): [this argument represents the bounds of the box]
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def __init__(self, center, radius, dimension): """[summary]Initialization of Box's parameters Args: args ([numpy array list]): [this argument represents the bounds of the box] """ self.dim = dimension self.rad = radius self.cent = center
171
179
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
__contains__
[summary]This method tests if an element (args) is inside the ball Args: args ([numpy array list]): [the element to test] Returns: [bool]: [True if the element is inside the ball , False if not]
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def __contains__(self, args): """[summary]This method tests if an element (args) is inside the ball Args: args ([numpy array list]): [the element to test] Returns: [bool]: [True if the element is inside the ball , False if not] """ # * same remarks a...
181
198
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
center
[summary] determinate the center of the ball Returns: [numpy array list]: [the center of the ball]
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
def center(self): """[summary] determinate the center of the ball Returns: [numpy array list]: [the center of the ball] """ # * interesting try # * exploit numpy vectorization power # ? how about np.mean(self.bounds) c = np.zeros(self.__len__()) ...
236
248
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
_get_bbox_regression_labels
Bounding-box regression targets are stored in a compact form in the roidb. This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). The loss weights are similarly expanded. Returns: bbox_target_data (ndarray): N x 4K blob of regression ta...
# -------------------------------------------------------- # Adapted from Faster R-CNN (https://github.com/rbgirshick/py-faster-rcnn) # Written by Danfei Xu # -------------------------------------------------------- """Compute minibatch blobs for training a Fast R-CNN network.""" import numpy as np import numpy.rando...
def _get_bbox_regression_labels(bbox_target_data, num_classes): """Bounding-box regression targets are stored in a compact form in the roidb. This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). The loss weights are sim...
279
301
# -------------------------------------------------------- # Adapted from Faster R-CNN (https://github.com/rbgirshick/py-faster-rcnn) # Written by Danfei Xu # -------------------------------------------------------- """Compute minibatch blobs for training a Fast R-CNN network.""" import numpy as np import numpy.rando...
_chain_future
Chain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future.
import concurrent.futures import threading from asyncio import coroutines from asyncio.events import AbstractEventLoop from asyncio.futures import Future import attr import uuid import asyncio from asyncio import ensure_future from typing import Any, Union, Coroutine, Callable, Generator, TypeVar, \ ...
def _chain_future( source: Union[concurrent.futures.Future, Future], destination: Union[concurrent.futures.Future, Future]) -> None: """Chain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cance...
125
171
import concurrent.futures import threading from asyncio import coroutines from asyncio.events import AbstractEventLoop from asyncio.futures import Future import attr import uuid import asyncio from asyncio import ensure_future from typing import Any, Union, Coroutine, Callable, Generator, TypeVar, \ ...
_get_through_model
Get the "through" model associated with this field. Need to handle things differently for Django1.1 vs Django1.2 In 1.1 through is a string and through_model has class In 1.2 through is the class
from django.db import models from django.db.models.query import QuerySet, Q from django.db.models.base import ModelBase from django.db.models.fields.related import RelatedField from django.conf import settings from utils import NestedSet from signals import pre_publish, post_publish # this takes some inspiration from...
def _get_through_model(self, field_object): ''' Get the "through" model associated with this field. Need to handle things differently for Django1.1 vs Django1.2 In 1.1 through is a string and through_model has class In 1.2 through is the class ''' through = fi...
244
256
from django.db import models from django.db.models.query import QuerySet, Q from django.db.models.base import ModelBase from django.db.models.fields.related import RelatedField from django.conf import settings from utils import NestedSet from signals import pre_publish, post_publish # this takes some inspiration from...
get_text_width
Function that utilizes ``wcswidth`` or ``wcwidth`` to determine the number of columns used to display a text string. We try first with ``wcswidth``, and fallback to iterating each character and using wcwidth individually, falling back to a value of 0 for non-printable wide characters On Py2, this depends on ``locale....
# (c) 2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
def get_text_width(text): """Function that utilizes ``wcswidth`` or ``wcwidth`` to determine the number of columns used to display a text string. We try first with ``wcswidth``, and fallback to iterating each character and using wcwidth individually, falling back to a value of 0 for non-printable w...
79
144
# (c) 2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
feature_evaluation
Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation between feature and response - Plot saved under given folder with file name including feature name Parameters ---------- X : DataFrame of shape (n_samples, n_features) ...
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression from IMLearn.metrics import * from typing import NoReturn import numpy as np import pandas as pd import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pio.templates.default = "simple_whi...
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn: """ Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation between feature and response - P...
41
72
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression from IMLearn.metrics import * from typing import NoReturn import numpy as np import pandas as pd import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pio.templates.default = "simple_whi...
get
Get an existing FirewallRule resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Option...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __al...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'FirewallRule': """ Get an existing FirewallRule resource's state with the given name, id, and optional extra properties used to qualify the lookup. ...
80
96
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __al...
evaluate
Predict with custom classifier model. Parameters: estimator: Fitted estimator. X: Input test data. y: Labels for test data. Returns: Predicted labels.
import matplotlib.pyplot as plt, streamlit as st from typing import Iterable, Union from sklearn.metrics import classification_report from sklearn.metrics import roc_curve, auc, RocCurveDisplay def train(estimator: object, X: Iterable[Union[int, float]], y: Iterable): """ Train custom classifier model. P...
def evaluate(estimator: object, X: Iterable[Union[int, float]], y: Iterable): """ Predict with custom classifier model. Parameters: estimator: Fitted estimator. X: Input test data. y: Labels for test data. Returns: Predicted labels. """ pred = estimator.predict(...
49
78
import matplotlib.pyplot as plt, streamlit as st from typing import Iterable, Union from sklearn.metrics import classification_report from sklearn.metrics import roc_curve, auc, RocCurveDisplay def train(estimator: object, X: Iterable[Union[int, float]], y: Iterable): """ Train custom classifier model...
fit_shifts
Fits (non-iteratively and without sigma-clipping) a displacement transformation only between input lists of positions ``xy`` and ``uv``. When weights are provided, a weighted fit is performed. Parameter descriptions and return values are identical to those in `iter_linear_fit`, except returned ``fit`` dictionary does n...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ A module that provides algorithms for performing linear fit between sets of 2D points. :Authors: Mihai Cara, Warren Hack :License: :doc:`../LICENSE` """ import logging import numbers import numpy as np from .linalg import inv from . import __versio...
def fit_shifts(xy, uv, wxy=None, wuv=None): """ Fits (non-iteratively and without sigma-clipping) a displacement transformation only between input lists of positions ``xy`` and ``uv``. When weights are provided, a weighted fit is performed. Parameter descriptions and return values are identical to those...
356
412
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ A module that provides algorithms for performing linear fit between sets of 2D points. :Authors: Mihai Cara, Warren Hack :License: :doc:`../LICENSE` """ import logging import numbers import numpy as np from .linalg import inv from . import __versio...
_encode_files
Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tup...
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
@staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. ...
114
176
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
iter_content
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be ...
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This i...
737
790
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
iter_lines
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe.
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is ...
792
821
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
json
Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json.
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(sel...
881
905
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
close
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.*
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() ...
950
961
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE...
initialize
Initialize a module. Args: module (``torch.nn.Module``): the module will be initialized. init_cfg (dict | list[dict]): initialization configuration dict to define initializer. OpenMMLab has implemented 6 initializers including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``, ``Kaiming...
#!/usr/bin/env python # -*- coding=utf8 -*- """ # Author: achao # File Name: weight_init.py # Description: """ import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from deep3dmap.core.utils import Registry, build_from_cfg, get_logger, print_log INITIA...
def initialize(module, init_cfg): """Initialize a module. Args: module (``torch.nn.Module``): the module will be initialized. init_cfg (dict | list[dict]): initialization configuration dict to define initializer. OpenMMLab has implemented 6 initializers including ``Const...
556
625
#!/usr/bin/env python # -*- coding=utf8 -*- """ # Author: achao # File Name: weight_init.py # Description: """ import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from deep3dmap.core.utils import Registry, build_from_cfg, get_logger, print_log INITIA...
patch_settings
Merge settings with global cms settings, so all required attributes will exist. Never override, just append non existing settings. Also check for setting inconsistencies if settings.DEBUG
# -*- coding: utf-8 -*- from cms.exceptions import CMSDeprecationWarning from django.conf import settings from patch import post_patch, post_patch_check, pre_patch import warnings # MASKED: patch_settings function (lines 9-37) patch_settings.ALREADY_PATCHED = False
def patch_settings(): """Merge settings with global cms settings, so all required attributes will exist. Never override, just append non existing settings. Also check for setting inconsistencies if settings.DEBUG """ if patch_settings.ALREADY_PATCHED: return patch_settings.ALREADY_P...
9
37
# -*- coding: utf-8 -*- from cms.exceptions import CMSDeprecationWarning from django.conf import settings from patch import post_patch, post_patch_check, pre_patch import warnings def patch_settings(): """Merge settings with global cms settings, so all required attributes will exist. Never override, just app...
list_database_account_keys
The access keys for the given database account. :param str account_name: Cosmos DB database account name. :param str resource_group_name: Name of an Azure resource group.
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
def list_database_account_keys(account_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListDatabaseAccountKeysResult: """ The access keys for the given database account. ...
81
104
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
run_recipe
Given a recipe, calls the appropriate query and returns the result. The provided recipe name is used to make a call to the modules. :param str recipe: name of the recipe to be run. :param list args: remainder arguments that were unparsed. :param Configuration config: config object. :returns: string
from __future__ import print_function, absolute_import import importlib import logging import os from argparse import ArgumentParser from six import string_types from adr.formatter import all_formatters from .errors import MissingDataError log = logging.getLogger('adr') here = os.path.abspath(os.path.dirname(__file...
def run_recipe(recipe, args, config): """Given a recipe, calls the appropriate query and returns the result. The provided recipe name is used to make a call to the modules. :param str recipe: name of the recipe to be run. :param list args: remainder arguments that were unparsed. :param Configurati...
95
116
from __future__ import print_function, absolute_import import importlib import logging import os from argparse import ArgumentParser from six import string_types from adr.formatter import all_formatters from .errors import MissingDataError log = logging.getLogger('adr') here = os.path.abspath(os.path.dirname(__file...
read_args
Reads command line arguments. Returns: Parsed arguments.
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize # MASKED: read_args function (lines 10-18) def plane_err(data,coeffs): '''Calculates the total squared error of the data wrt a ...
def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', type=str, help='path to .csv file', default='orbit.csv') parser.add_argument('-u', '--units', type=str, help='units of distance (m or km)', defa...
10
18
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
conv_to_2D
Finds coordinates of points in a plane wrt a basis. Given a list of points in a plane, and a basis of the plane, this function returns the coordinates of those points wrt this basis. Arguments: points: A numpy array of points. x: One vector of the basis. y: Another vector of the basis. Returns: Coordinates of the po...
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
def conv_to_2D(points,x,y): '''Finds coordinates of points in a plane wrt a basis. Given a list of points in a plane, and a basis of the plane, this function returns the coordinates of those points wrt this basis. Arguments: points: A numpy array of points. x: One vector ...
60
79
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
cart_to_pol
Converts a list of cartesian coordinates into polar ones. Arguments: points: The list of points in the format [x,y]. Returns: A list of polar coordinates in the format [radius,angle].
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
def cart_to_pol(points): '''Converts a list of cartesian coordinates into polar ones. Arguments: points: The list of points in the format [x,y]. Returns: A list of polar coordinates in the format [radius,angle].''' pol = np.empty(points.shape) pol[:,0] = np.sqrt(points[:,0]**2...
81
94
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
ellipse_err
Calculates the total squared error of the data wrt an ellipse. params is a 3 element array used to define an ellipse. It contains 3 elements a,e, and t0. a is the semi-major axis e is the eccentricity t0 is the angle of the major axis wrt the x-axis. These 3 elements define an ellipse with one focus at origin. Equat...
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
def ellipse_err(polar_coords,params): '''Calculates the total squared error of the data wrt an ellipse. params is a 3 element array used to define an ellipse. It contains 3 elements a,e, and t0. a is the semi-major axis e is the eccentricity t0 is the angle of the major axis wrt...
96
124
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
leakyrelu
leakyrelu激活函数 Args: x (Tensor): input leak (int): x<0时的斜率 Returns: Tensor
import tensorflow as tf # MASKED: leakyrelu function (lines 4-16)
def leakyrelu(x, leak=0.01): """ leakyrelu激活函数 Args: x (Tensor): input leak (int): x<0时的斜率 Returns: Tensor """ f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * x + f2 * tf.abs(x)
4
16
import tensorflow as tf def leakyrelu(x, leak=0.01): """ leakyrelu激活函数 Args: x (Tensor): input leak (int): x<0时的斜率 Returns: Tensor """ f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * x + f2 * tf.abs(x)
est_fpos_rate
Estimate false positive rate of a single-token signature. Estimates using the 'tokensplit' and trace-modeling methods, and returns the higher (most pessimistic of the two). Note that both of these estimates are strictly equal to or higher than the actual fraction of streams that 'token' occurs in within the trace.
# Polygraph (release 0.1) # Signature generation algorithms for polymorphic worms # # Copyright (c) 2004-2005, Intel Corporation # All Rights Reserved # # This software is distributed under the terms of the Eclipse Public # License, Version 1.0 which can be found in the file named LICENSE. # ANY ...
def est_fpos_rate(token, trace=None, stats=None): """ Estimate false positive rate of a single-token signature. Estimates using the 'tokensplit' and trace-modeling methods, and returns the higher (most pessimistic of the two). Note that both of these estimates are strictly equal to or higher th...
60
95
# Polygraph (release 0.1) # Signature generation algorithms for polymorphic worms # # Copyright (c) 2004-2005, Intel Corporation # All Rights Reserved # # This software is distributed under the terms of the Eclipse Public # License, Version 1.0 which can be found in the file named LICENSE. # ANY ...
input_fn
Input function which provides a single batch for train or eval. Returns: A `tf.data.Dataset` object.
# 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 input_fn(self): """Input function which provides a single batch for train or eval. Returns: A `tf.data.Dataset` object. """ if self.data_dir is None: tf.logging.info('Using fake input.') return self.input_fn_null() # Shuffle the filenames to ensure better randomization. ...
100
138
# 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...
login
Log user in using GitHub OAuth arguments: :request: GET HTTP request returns: Redirects to index
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
def login(request): """ Log user in using GitHub OAuth arguments: :request: GET HTTP request returns: Redirects to index """ # Create keys if not yet there! if not request.session.get('github_token'): request.session['github_token'] = None # To keep API token ...
59
83
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
callback
GitHub redirect here, then retrieves token for API arguments: :request: GET HTTP request returns: Redirects to index
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
def callback(request): """ GitHub redirect here, then retrieves token for API arguments: :request: GET HTTP request returns: Redirects to index """ # Get code supplied by github code = request.GET.get('code') # Payload to fetch payload = {'client_id': GITHUB_CLIENT...
86
117
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
logout
Logs user out but keep authorization ot OAuth GitHub arguments: :request: GET HTTP request returns: Redirects to index
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
def logout(request): """ Logs user out but keep authorization ot OAuth GitHub arguments: :request: GET HTTP request returns: Redirects to index """ # Flush the session request.session['github_token'] = None request.session['github_info'] = None return HttpResponse...
120
135
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
recommendations
Get recommended packages for the repo arguments: :request: GET/POST HTTP request :name: repo name returns: Rendered recommendation page
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
def recommendations(request, name): """ Get recommended packages for the repo arguments: :request: GET/POST HTTP request :name: repo name returns: Rendered recommendation page """ # Convert encoded URL back to string e.g. hello%2world -> hello/world repo_name = url...
188
240
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
recommendations_json
Get recommended packages for the repo in JSON format arguments: :request: GET HTTP request :name: repo name returns: JSON object with recommendations
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
def recommendations_json(request, name): """ Get recommended packages for the repo in JSON format arguments: :request: GET HTTP request :name: repo name returns: JSON object with recommendations """ # Convert encoded URL back to string e.g. hello%2world -> hello/world ...
243
286
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
recommendations_service_api
Returns package recommendations for API POST call without authentication arguments: :request: POST request of application/json type returns: list of package recommendations
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
@csrf_exempt def recommendations_service_api(request): """ Returns package recommendations for API POST call without authentication arguments: :request: POST request of application/json type returns: list of package recommendations """ if request.method == 'POST': # Fe...
289
369
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
link_iterable_by_fields
Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``. The database to be linked must have uniqueness for each object for the given ``fields``. If ``kind``, limit objects in ``unlinked`` of type ``kind``. If ``relink``, link to objects which already have an ``input``. Other...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
def link_iterable_by_fields(unlinked, other=None, fields=None, kind=None, internal=False, relink=False): """Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``. The database to be linked must have uniqueness for each object for the given ...
25
71
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
assign_only_product_as_production
Assign only product as reference product. Skips datasets that already have a reference product or no production exchanges. Production exchanges must have a ``name`` and an amount. Will replace the following activity fields, if not already specified: * 'name' - name of reference product * 'unit' - unit of reference p...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
def assign_only_product_as_production(db): """Assign only product as reference product. Skips datasets that already have a reference product or no production exchanges. Production exchanges must have a ``name`` and an amount. Will replace the following activity fields, if not already specified: * 'na...
74
97
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
link_technosphere_by_activity_hash
Link technosphere exchanges using ``activity_hash`` function. If ``external_db_name``, link against a different database; otherwise link internally. If ``fields``, link using only certain fields.
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
def link_technosphere_by_activity_hash(db, external_db_name=None, fields=None): """Link technosphere exchanges using ``activity_hash`` function. If ``external_db_name``, link against a different database; otherwise link internally. If ``fields``, link using only certain fields.""" TECHNOSPHERE_TYPES =...
100
117
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
AccountListVolumes
Show the list of volumes for an account Args: account_name: the name of the account account_id: the ID of the account by_id: show volume IDs instead of names mvip: the management IP of the cluster username: the admin user of the cluster pa...
#!/usr/bin/env python """ This action will display a list of volumes for an account """ from libsf.apputil import PythonApp from libsf.argutil import SFArgumentParser, GetFirstLine, SFArgFormatter from libsf.logutil import GetLogger, logargs from libsf.sfcluster import SFCluster from libsf.util import ValidateAndDefa...
@logargs @ValidateAndDefault({ # "arg_name" : (arg_type, arg_default) "account_name" : (OptionalValueType(StrType), None), "account_id" : (OptionalValueType(SolidFireIDType), None), "by_id" : (BoolType, False), "mvip" : (IPv4AddressType, sfdefaults.mvip), "username" : (StrType, sfdefaults.userna...
17
87
#!/usr/bin/env python """ This action will display a list of volumes for an account """ from libsf.apputil import PythonApp from libsf.argutil import SFArgumentParser, GetFirstLine, SFArgFormatter from libsf.logutil import GetLogger, logargs from libsf.sfcluster import SFCluster from libsf.util import ValidateAndDefa...
_add_processname_features
Add process name default features. Parameters ---------- output_df : pd.DataFrame The dataframe to add features to force : bool If True overwrite existing feature columns path_separator : str Path separator for OS
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- r""" event...
def _add_processname_features( output_df: pd.DataFrame, force: bool, path_separator: str ): """ Add process name default features. Parameters ---------- output_df : pd.DataFrame The dataframe to add features to force : bool If True overwrite existing feature columns path...
316
347
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- r""" event...
_add_commandline_features
Add commandline default features. Parameters ---------- output_df : pd.DataFrame The dataframe to add features to force : bool If True overwrite existing feature columns
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- r""" event...
def _add_commandline_features(output_df: pd.DataFrame, force: bool): """ Add commandline default features. Parameters ---------- output_df : pd.DataFrame The dataframe to add features to force : bool If True overwrite existing feature columns """ if "commandlineLen" not...
350
382
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- r""" event...
user_to_dict
Returns a dictionary based on a user object. Extra attributes to be retrieved must be set in this module's configuration. :param user: User object: an instance the custom user model. :returns: A dictionary with user data.
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
def user_to_dict(self, user): """Returns a dictionary based on a user object. Extra attributes to be retrieved must be set in this module's configuration. :param user: User object: an instance the custom user model. :returns: A dictionary with user d...
133
149
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
default_token_validator
Validates a token. Tokens are random strings used to authenticate temporarily. They are used to validate sessions or service requests. :param user_id: User id. :param token: Token to be checked. :param token_ts: Optional token timestamp used to pre-validate the token age. :returns: A tuple ``(user_dic...
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
def default_token_validator(self, user_id, token, token_ts=None): """Validates a token. Tokens are random strings used to authenticate temporarily. They are used to validate sessions or service requests. :param user_id: User id. :param token: Token t...
284
321
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
get_user_by_session
Returns a user based on the current session. :param save_session: If True, saves the user in the session if authentication succeeds. :returns: A user dict or None.
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
def get_user_by_session(self, save_session=True): """Returns a user based on the current session. :param save_session: If True, saves the user in the session if authentication succeeds. :returns: A user dict or None. """ if self._user is None: ...
351
370
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
get_user_by_password
Returns a user based on password credentials. :param auth_id: Authentication id. :param password: User password. :param remember: If True, saves permanent sessions. :param save_session: If True, saves the user in the session if authentication succeeds. :param silent: If True, raises an exception if...
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
def get_user_by_password(self, auth_id, password, remember=False, save_session=True, silent=False): """Returns a user based on password credentials. :param auth_id: Authentication id. :param password: User password. :param remembe...
430
461
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
set_session
Saves a user in the session. :param user: A dictionary with user data. :param token: A unique token to be persisted. If None, a new one is created. :param token_ts: Token timestamp. If None, a new one is created. :param cache_ts: Token cache timestamp. If None, a new one is created. :remember: If T...
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
def set_session(self, user, token=None, token_ts=None, cache_ts=None, remember=False, **session_args): """Saves a user in the session. :param user: A dictionary with user data. :param token: A unique token to be persisted. If None, a new one is cr...
470
508
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
get_session_data
Returns the session data as a dictionary. :param pop: If True, removes the session. :returns: A deserialized session, or None.
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
def get_session_data(self, pop=False): """Returns the session data as a dictionary. :param pop: If True, removes the session. :returns: A deserialized session, or None. """ func = self.session.pop if pop else self.session.get rv = func('_user'...
518
529
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
stage
Parametrize tests for Ingress/Egress stage testing. Args: request: A fixture to interact with Pytest data. duthosts: All DUTs belong to the testbed. rand_one_dut_hostname: hostname of a random chosen dut to run test. Returns: str: The ACL stage to be tested.
from tests.common import reboot, port_toggle import os import time import random import logging import pprint import pytest import json import ptf.testutils as testutils import ptf.mask as mask import ptf.packet as packet from abc import ABCMeta, abstractmethod from collections import defaultdict from tests.common i...
@pytest.fixture(scope="module", params=["ingress", "egress"]) def stage(request, duthosts, rand_one_dut_hostname): """Parametrize tests for Ingress/Egress stage testing. Args: request: A fixture to interact with Pytest data. duthosts: All DUTs belong to the testbed. rand_one_dut_hostnam...
286
305
from tests.common import reboot, port_toggle import os import time import random import logging import pprint import pytest import json import ptf.testutils as testutils import ptf.mask as mask import ptf.packet as packet from abc import ABCMeta, abstractmethod from collections import defaultdict from tests.common i...
acl_table
Apply ACL table configuration and remove after tests. Args: duthosts: All DUTs belong to the testbed. rand_one_dut_hostname: hostname of a random chosen dut to run test. setup: Parameters for the ACL tests. stage: The ACL stage under test. ip_version: The IP version under test Yields: The ACL ...
from tests.common import reboot, port_toggle import os import time import random import logging import pprint import pytest import json import ptf.testutils as testutils import ptf.mask as mask import ptf.packet as packet from abc import ABCMeta, abstractmethod from collections import defaultdict from tests.common i...
@pytest.fixture(scope="module") def acl_table(duthosts, rand_one_dut_hostname, setup, stage, ip_version): """Apply ACL table configuration and remove after tests. Args: duthosts: All DUTs belong to the testbed. rand_one_dut_hostname: hostname of a random chosen dut to run test. setup: P...
324
372
from tests.common import reboot, port_toggle import os import time import random import logging import pprint import pytest import json import ptf.testutils as testutils import ptf.mask as mask import ptf.packet as packet from abc import ABCMeta, abstractmethod from collections import defaultdict from tests.common i...
compute_ade
Compute the average displacement error for a set of K predicted trajectories (for the same actor). Args: forecasted_trajectories: (K, N, 2) predicted trajectories, each N timestamps in length. gt_trajectory: (N, 2) ground truth trajectory. Returns: (K,) Average displacement error for each of the predicted...
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber # MASKED: compute_ade function (lines 9-22) def compute_fde(forecasted_trajecto...
def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNumber) -> NDArrayFloat: """Compute the average displacement error for a set of K predicted trajectories (for the same actor). Args: forecasted_trajectories: (K, N, 2) predicted trajectories, each N timestamps in length. ...
9
22
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNum...
compute_fde
Compute the final displacement error for a set of K predicted trajectories (for the same actor). Args: forecasted_trajectories: (K, N, 2) predicted trajectories, each N timestamps in length. gt_trajectory: (N, 2) ground truth trajectory, FDE will be evaluated against true position at index `N-1`. Returns: ...
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNum...
def compute_fde(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNumber) -> NDArrayFloat: """Compute the final displacement error for a set of K predicted trajectories (for the same actor). Args: forecasted_trajectories: (K, N, 2) predicted trajectories, each N timestamps in length. ...
25
38
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNum...
compute_is_missed_prediction
Compute whether each of K predicted trajectories (for the same actor) missed by more than a distance threshold. Args: forecasted_trajectories: (K, N, 2) predicted trajectories, each N timestamps in length. gt_trajectory: (N, 2) ground truth trajectory, miss will be evaluated against true position at index `N-1...
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNum...
def compute_is_missed_prediction( forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNumber, miss_threshold_m: float = 2.0, ) -> NDArrayBool: """Compute whether each of K predicted trajectories (for the same actor) missed by more than a distance threshold. Args: forecasted_trajec...
41
58
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNum...
undo_logger_setup
Undoes the automatic logging setup done by OpenAI Gym. You should call this function if you want to manually configure logging yourself. Typical usage would involve putting something like the following at the top of your script: gym.undo_logger_setup() logger = logging.getLogger() logger.addHandler(logging.StreamHandl...
import logging import sys import gym logger = logging.getLogger(__name__) root_logger = logging.getLogger() requests_logger = logging.getLogger('requests') # Set up the default handler formatter = logging.Formatter('[%(asctime)s] %(message)s') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatt...
def undo_logger_setup(): """Undoes the automatic logging setup done by OpenAI Gym. You should call this function if you want to manually configure logging yourself. Typical usage would involve putting something like the following at the top of your script: gym.undo_logger_setup() logger = loggi...
25
37
import logging import sys import gym logger = logging.getLogger(__name__) root_logger = logging.getLogger() requests_logger = logging.getLogger('requests') # Set up the default handler formatter = logging.Formatter('[%(asctime)s] %(message)s') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatt...
_predict_var
predict values for conditional variance V(endog | exog) Parameters ---------- params : array_like The model parameters. This is only used to extract extra params like dispersion parameter. mu : array_like Array of mean predictions for main model. prob_inlf : array_like Array of predicted probabilities ...
__all__ = ["ZeroInflatedPoisson", "ZeroInflatedGeneralizedPoisson", "ZeroInflatedNegativeBinomialP"] import warnings import numpy as np import statsmodels.base.model as base import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.discrete.discrete_model impo...
def _predict_var(self, params, mu, prob_infl): """predict values for conditional variance V(endog | exog) Parameters ---------- params : array_like The model parameters. This is only used to extract extra params like dispersion parameter. mu : array_l...
665
684
__all__ = ["ZeroInflatedPoisson", "ZeroInflatedGeneralizedPoisson", "ZeroInflatedNegativeBinomialP"] import warnings import numpy as np import statsmodels.base.model as base import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.discrete.discrete_model impo...
_predict_var
predict values for conditional variance V(endog | exog) Parameters ---------- params : array_like The model parameters. This is only used to extract extra params like dispersion parameter. mu : array_like Array of mean predictions for main model. prob_inlf : array_like Array of predicted probabilities ...
__all__ = ["ZeroInflatedPoisson", "ZeroInflatedGeneralizedPoisson", "ZeroInflatedNegativeBinomialP"] import warnings import numpy as np import statsmodels.base.model as base import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.discrete.discrete_model impo...
def _predict_var(self, params, mu, prob_infl): """predict values for conditional variance V(endog | exog) Parameters ---------- params : array_like The model parameters. This is only used to extract extra params like dispersion parameter. mu : array_l...
803
824
__all__ = ["ZeroInflatedPoisson", "ZeroInflatedGeneralizedPoisson", "ZeroInflatedNegativeBinomialP"] import warnings import numpy as np import statsmodels.base.model as base import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.discrete.discrete_model impo...
_predict_var
predict values for conditional variance V(endog | exog) Parameters ---------- params : array_like The model parameters. This is only used to extract extra params like dispersion parameter. mu : array_like Array of mean predictions for main model. prob_inlf : array_like Array of predicted probabilities ...
__all__ = ["ZeroInflatedPoisson", "ZeroInflatedGeneralizedPoisson", "ZeroInflatedNegativeBinomialP"] import warnings import numpy as np import statsmodels.base.model as base import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.discrete.discrete_model impo...
def _predict_var(self, params, mu, prob_infl): """predict values for conditional variance V(endog | exog) Parameters ---------- params : array_like The model parameters. This is only used to extract extra params like dispersion parameter. mu : array_l...
919
940
__all__ = ["ZeroInflatedPoisson", "ZeroInflatedGeneralizedPoisson", "ZeroInflatedNegativeBinomialP"] import warnings import numpy as np import statsmodels.base.model as base import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.discrete.discrete_model impo...
reproduce
Reproduce the specified experiments. Args: revs: If revs is not specified, all stashed experiments will be reproduced. keep_stash: If True, stashed experiments will be preserved if they fail to reproduce successfully.
import logging import os import re import signal from collections import defaultdict, namedtuple from concurrent.futures import CancelledError, ProcessPoolExecutor, wait from contextlib import contextmanager from functools import wraps from multiprocessing import Manager from typing import Iterable, Mapping, Optional ...
@scm_locked def reproduce( self, revs: Optional[Iterable] = None, keep_stash: Optional[bool] = True, **kwargs, ): """Reproduce the specified experiments. Args: revs: If revs is not specified, all stashed experiments will be reprodu...
357
419
import logging import os import re import signal from collections import defaultdict, namedtuple from concurrent.futures import CancelledError, ProcessPoolExecutor, wait from contextlib import contextmanager from functools import wraps from multiprocessing import Manager from typing import Iterable, Mapping, Optional ...
create_model
Creates a CNN model. Args: model_input: 'batch' x 'num_features' matrix of input features. vocab_size: The number of classes in the dataset. Returns: A dictionary with a tensor containing the probability predictions of the model in the 'predictions' key. The dimensions of the tensor are batch_size x num_cla...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
def create_model(self, model_input, vocab_size, l2_penalty=1e-8, **unused_params): """Creates a CNN model. Args: model_input: 'batch' x 'num_features' matrix of input features. vocab_size: The number of classes in the dat...
33
68
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
create_model
Creates a ResNet model. Args: model_input: 'batch' x 'num_features' matrix of input features. vocab_size: The number of classes in the dataset. Returns: A dictionary with a tensor containing the probability predictions of the model in the 'predictions' key. The dimensions of the tensor are batch_size x num_...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
def create_model(self, model_input, vocab_size, l2_penalty=1e-8, **unused_params): """Creates a ResNet model. Args: model_input: 'batch' x 'num_features' matrix of input features. vocab_size: The number of classes in the ...
74
122
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
create_model
Creates a Mixture of (Logistic) Experts model. The model consists of a per-class softmax distribution over a configurable number of logistic classifiers. One of the classifiers in the mixture is not trained, and always predicts 0. Args: model_input: 'batch_size' x 'num_features' matrix of input features. vocab...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
def create_model(self, model_input, vocab_size, num_mixtures=None, l2_penalty=1e-8, **unused_params): """Creates a Mixture of (Logistic) Experts model. The model consists of a per-class softmax distribution over a...
155
208
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
get_corner_loss_lidar
Args: pred_bbox3d: (N, 7) float Tensor. gt_bbox3d: (N, 7) float Tensor. Returns: corner_loss: (N) float Tensor.
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def get_corner_loss_lidar(pred_bbox3d: torch.Tensor, gt_bbox3d: torch.Tensor): """ Args: pred_bbox3d: (N, 7) float Tensor. gt_bbox3d: (N, 7) float Tensor. Returns: corner_loss: (N) float Tensor. """ assert pred_bbox3d.shape[0] == gt_bbox3d.shape[0] pred_box_corners = bo...
212
235
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
__init__
Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples.
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ # MASKED: __in...
def __init__(self, gamma: float = 2.0, alpha: float = 0.25): """ Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples. """ super().__init__() self.alp...
15
23
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
forward
Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: weighted_loss: (B, #anchors, #classes) float...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classifica...
45
73
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
__init__
Args: beta: Scalar float. L1 to L2 change point. For beta values < 1e-5, L1 loss is computed. code_weights: (#codes) float list if not None. Code-wise weights.
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def __init__(self, beta: float = 1.0 / 9.0, code_weights: list = None): """ Args: beta: Scalar float. L1 to L2 change point. For beta values < 1e-5, L1 loss is computed. code_weights: (#codes) float list if not None. Code-wise w...
86
99
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
forward
Args: input: (B, #anchors, #codes) float tensor. Ecoded predicted locations of objects. target: (B, #anchors, #codes) float tensor. Regression targets. weights: (B, #anchors) float tensor if not None. Returns: loss: (B, #anchors) float tensor. Weighted smooth l1 loss without red...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor = None): """ Args: input: (B, #anchors, #codes) float tensor. Ecoded predicted locations of objects. target: (B, #anchors, #codes) float tensor. Regression targe...
111
138
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
__init__
Args: code_weights: (#codes) float list if not None. Code-wise weights.
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def __init__(self, code_weights: list = None): """ Args: code_weights: (#codes) float list if not None. Code-wise weights. """ super(WeightedL1Loss, self).__init__() if code_weights is not None: self.code_weights = np.array(code_weights...
142
151
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
forward
Args: input: (B, #anchors, #codes) float tensor. Ecoded predicted locations of objects. target: (B, #anchors, #codes) float tensor. Regression targets. weights: (B, #anchors) float tensor if not None. Returns: loss: (B, #anchors) float tensor. Weighted smooth l1 loss without red...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor = None): """ Args: input: (B, #anchors, #codes) float tensor. Ecoded predicted locations of objects. target: (B, #anchors, #codes) float tensor. Regression targe...
153
180
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
forward
Args: input: (B, #anchors, #classes) float tensor. Predited logits for each class. target: (B, #anchors, #classes) float tensor. One-hot classification targets. weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: loss: (B, #anchors) float tensor. Weighted ...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predited logits for each class. target: (B, #anchors, #classes) float tensor. One-hot classification tar...
192
209
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
_neg_loss
Modified focal loss. Exactly the same as CornerNet. Runs faster and costs a little bit more memory Arguments: pred (batch x c x h x w) gt_regr (batch x c x h x w)
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def _neg_loss(self, pred, gt): """ Modified focal loss. Exactly the same as CornerNet. Runs faster and costs a little bit more memory Arguments: pred (batch x c x h x w) gt_regr (batch x c x h x w) """ pos_inds = gt.eq(1).float() ne...
244
270
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
_reg_loss
L1 regression loss Arguments: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects)
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def _reg_loss(self, regr, gt_regr, mask): """ L1 regression loss Arguments: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects) """ num = mask.float().sum() mask = mask.unsqueeze(2).expand_as(...
306
327
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
__init__
Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples.
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def __init__(self, gamma: float = 2.0, alpha: float = 0.25): """ Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples. """ super(ForegroundFocalLoss, self).__...
340
348
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
forward
Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: weighted_loss: (B, #anchors, #classes) float...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def forward(self, input: torch.Tensor, target: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets ...
370
395
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
_smooth_reg_loss
L1 regression loss Arguments: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects)
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def _smooth_reg_loss(self, regr, gt_regr, mask, sigma=3): """ L1 regression loss Arguments: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects) """ num = mask.float().sum() mask = mask.unsqueeze...
410
438
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
__init__
Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples.
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def __init__(self, gamma: float = 2.0, alpha: float = 0.25, reduction='mean'): """ Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples. """ super(E2ESigmoidF...
448
457
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
forward
Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: weighted_loss: (B, #anchors, #classes) float...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
def forward(self, input: torch.Tensor, target: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets ...
478
503
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pcdet.ops.iou3d_nms_diff.iou3d_nms_diff_utils import boxes_iou3d_gpu_differentiable from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init...
parse_model_config_params
Args: model_params: num_settings: random_state: Returns:
import numpy as np import yaml from dask.distributed import Client, LocalCluster, as_completed import argparse from os.path import exists, join from os import makedirs from mlmicrophysics.data import subset_data_files_by_date, assemble_data_files from sklearn.ensemble import RandomForestRegressor, RandomForestClassifie...
def parse_model_config_params(model_params, num_settings, random_state): """ Args: model_params: num_settings: random_state: Returns: """ param_distributions = dict() dist_types = dict(randint=randint, expon=expon, uniform=uniform) for param, param_value in model_p...
28
46
import numpy as np import yaml from dask.distributed import Client, LocalCluster, as_completed import argparse from os.path import exists, join from os import makedirs from mlmicrophysics.data import subset_data_files_by_date, assemble_data_files from sklearn.ensemble import RandomForestRegressor, RandomForestClassifie...
test_with_double_quoted_multiple_words
Test with double-quoted multiple words. A completed quote will trigger this. Unclosed quotes are ignored.
from __future__ import absolute_import, unicode_literals from unittest import TestCase as UnitTestCase import django from django.contrib.contenttypes.models import ContentType from django.core import serializers from django.core.exceptions import ImproperlyConfigured, ValidationError from django.test import TestCase,...
def test_with_double_quoted_multiple_words(self): """ Test with double-quoted multiple words. A completed quote will trigger this. Unclosed quotes are ignored. """ self.assertEqual(parse_tags('"one'), ['one']) self.assertEqual(parse_tags('"one two'), ['one', 'two']) ...
506
516
from __future__ import absolute_import, unicode_literals from unittest import TestCase as UnitTestCase import django from django.contrib.contenttypes.models import ContentType from django.core import serializers from django.core.exceptions import ImproperlyConfigured, ValidationError from django.test import TestCase,...
makedir
return a directory path object with the given name. If the directory does not yet exist, it will be created. You can use it to manage files likes e. g. store/retrieve database dumps across test sessions. :param name: must be a string not containing a ``/`` separator. Make sure the name contains your plugin or a...
""" merged implementation of the cache provider the name cache was not chosen to ensure pluggy automatically ignores the external pytest-cache """ from __future__ import absolute_import, division, print_function from collections import OrderedDict import py import six import attr import pytest import json import shu...
def makedir(self, name): """ return a directory path object with the given name. If the directory does not yet exist, it will be created. You can use it to manage files likes e. g. store/retrieve database dumps across test sessions. :param name: must be a string not contai...
58
73
""" merged implementation of the cache provider the name cache was not chosen to ensure pluggy automatically ignores the external pytest-cache """ from __future__ import absolute_import, division, print_function from collections import OrderedDict import py import six import attr import pytest import json import shu...
set
save value for the given key. :param key: must be a ``/`` separated value. Usually the first name is the name of your plugin or your application. :param value: must be of any combination of basic python types, including nested types like e. g. lists of dictionaries.
""" merged implementation of the cache provider the name cache was not chosen to ensure pluggy automatically ignores the external pytest-cache """ from __future__ import absolute_import, division, print_function from collections import OrderedDict import py import six import attr import pytest import json import shu...
def set(self, key, value): """ save value for the given key. :param key: must be a ``/`` separated value. Usually the first name is the name of your plugin or your application. :param value: must be of any combination of basic python types, including nested types...
96
118
""" merged implementation of the cache provider the name cache was not chosen to ensure pluggy automatically ignores the external pytest-cache """ from __future__ import absolute_import, division, print_function from collections import OrderedDict import py import six import attr import pytest import json import shu...
_compute_delta
Compute delta for given log_moments and eps. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) eps: the target epsilon. Returns: delta
# Copyright 2016 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 _compute_delta(log_moments, eps): """Compute delta for given log_moments and eps. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) eps: the target epsilon. Returns: delta """ min_delta = 1.0 for moment_order, log_moment in log_mome...
232
252
# Copyright 2016 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...
_compute_eps
Compute epsilon for given log_moments and delta. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) delta: the target delta. Returns: epsilon
# Copyright 2016 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 _compute_eps(log_moments, delta): """Compute epsilon for given log_moments and delta. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) delta: the target delta. Returns: epsilon """ min_eps = float("inf") for moment_order, log_momen...
255
273
# Copyright 2016 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...
compute_log_moment
Compute the log moment of Gaussian mechanism for given parameters. Args: q: the sampling ratio. sigma: the noise sigma. steps: the number of steps. lmbd: the moment order. verify: if False, only compute the symbolic version. If True, computes both symbolic and numerical solutions and verifies the results...
# Copyright 2016 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 compute_log_moment(q, sigma, steps, lmbd, verify=False, verbose=False): """Compute the log moment of Gaussian mechanism for given parameters. Args: q: the sampling ratio. sigma: the noise sigma. steps: the number of steps. lmbd: the moment order. verify: if False, only compute the symbolic ...
276
302
# Copyright 2016 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...
pacf_ols
Calculate partial autocorrelations Parameters ---------- x : 1d array observations of time series for which pacf is calculated nlags : int Number of lags for which pacf is returned. Lag 0 is not returned. Returns ------- pacf : 1d array partial autocorrelations, maxlag+1 elements Notes ----- This solves...
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
def pacf_ols(x, nlags=40): '''Calculate partial autocorrelations Parameters ---------- x : 1d array observations of time series for which pacf is calculated nlags : int Number of lags for which pacf is returned. Lag 0 is not returned. Returns ------- pacf : 1d array ...
525
557
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
ccovf
crosscovariance for 1D Parameters ---------- x, y : arrays time series data unbiased : boolean if True, then denominators is n-k, otherwise n Returns ------- ccovf : array autocovariance function Notes ----- This uses np.correlate which does full convolution. For very long time series it is recommended to ...
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
def ccovf(x, y, unbiased=True, demean=True): ''' crosscovariance for 1D Parameters ---------- x, y : arrays time series data unbiased : boolean if True, then denominators is n-k, otherwise n Returns ------- ccovf : array autocovariance function Notes ----...
626
658
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
periodogram
Returns the periodogram for the natural frequency of X Parameters ---------- X : array-like Array for which the periodogram is desired. Returns ------- pgram : array 1./len(X) * np.abs(np.fft.fft(X))**2 References ---------- Brockwell and Davis.
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
def periodogram(X): """ Returns the periodogram for the natural frequency of X Parameters ---------- X : array-like Array for which the periodogram is desired. Returns ------- pgram : array 1./len(X) * np.abs(np.fft.fft(X))**2 References ---------- Brockwe...
689
714
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
_sigma_est_kpss
Computes equation 10, p. 164 of Kwiatkowski et al. (1992). This is the consistent estimator for the variance.
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
def _sigma_est_kpss(resids, nobs, lags): """ Computes equation 10, p. 164 of Kwiatkowski et al. (1992). This is the consistent estimator for the variance. """ s_hat = sum(resids**2) for i in range(1, lags + 1): resids_prod = np.dot(resids[i:], resids[:nobs - i]) s_hat += 2 * resi...
1,295
1,304
""" Statistical tools for time series analysis """ from statsmodels.compat.python import (iteritems, range, lrange, string_types, lzip, zip, long) from statsmodels.compat.scipy import _next_regular import numpy as np from numpy.linalg import LinAlgError from scipy import stats f...
__init__
Args: dataclass_types: Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args. kwargs: (Optional) Passed to `argparse.ArgumentParser()` in the regular way.
import json import re import sys from argparse import ArgumentParser, ArgumentTypeError from enum import Enum from pathlib import Path from typing import Any, Iterable, List, NewType, Optional, Tuple, Union import dataclasses DataClass = NewType("DataClass", Any) DataClassType = NewType("DataClassType", Any) def st...
def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]], **kwargs): """ Args: dataclass_types: Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args. kwargs: (Optional) Pass...
48
61
import json import re import sys from argparse import ArgumentParser, ArgumentTypeError from enum import Enum from pathlib import Path from typing import Any, Iterable, List, NewType, Optional, Tuple, Union import dataclasses DataClass = NewType("DataClass", Any) DataClassType = NewType("DataClassType", Any) def st...
__init__
:param application: The application to associate this popup dialog with. :type application: :py:class:`.KingPhisherClientApplication` :param str hostname: The hostname associated with the key. :param key: The host's SSH key. :type key: :py:class:`paramiko.pkey.PKey`
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/client/dialogs/ssh_host_key.py # # 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 the above copyright #...
def __init__(self, application, hostname, key): """ :param application: The application to associate this popup dialog with. :type application: :py:class:`.KingPhisherClientApplication` :param str hostname: The hostname associated with the key. :param key: The host's SSH key. :type key: :py:class:`paramiko...
72
88
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/client/dialogs/ssh_host_key.py # # 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 the above copyright #...
__init__
:param application: The application which is using this policy. :type application: :py:class:`.KingPhisherClientApplication`
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/client/dialogs/ssh_host_key.py # # 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 the above copyright #...
def __init__(self, application): """ :param application: The application which is using this policy. :type application: :py:class:`.KingPhisherClientApplication` """ self.application = application self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__) super(MissingHostKeyPolicy,...
132
139
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/client/dialogs/ssh_host_key.py # # 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 the above copyright #...