body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
07f978470b07ed97966324846e4eff8bc73ddd87c29ed6b139953766445c0fe1
def peek(self): 'If alive then return (obj, func, args, kwargs);\n otherwise return None' info = self._registry.get(self) obj = (info and info.weakref()) if (obj is not None): return (obj, info.func, info.args, (info.kwargs or {}))
If alive then return (obj, func, args, kwargs); otherwise return None
numba/utils.py
peek
meawoppl/numba
1
python
def peek(self): 'If alive then return (obj, func, args, kwargs);\n otherwise return None' info = self._registry.get(self) obj = (info and info.weakref()) if (obj is not None): return (obj, info.func, info.args, (info.kwargs or {}))
def peek(self): 'If alive then return (obj, func, args, kwargs);\n otherwise return None' info = self._registry.get(self) obj = (info and info.weakref()) if (obj is not None): return (obj, info.func, info.args, (info.kwargs or {}))<|docstring|>If alive then return (obj, func, args, kwargs); otherwise return None<|endoftext|>
bc4aa50ab4a224d250af75b8697551e6eda9e55e7b1a785750a9037b735a021b
@property def alive(self): 'Whether finalizer is alive' return (self in self._registry)
Whether finalizer is alive
numba/utils.py
alive
meawoppl/numba
1
python
@property def alive(self): return (self in self._registry)
@property def alive(self): return (self in self._registry)<|docstring|>Whether finalizer is alive<|endoftext|>
b399c07daafe84ed605db04081d9703cbd10c19065674a5a8fcf89643c69d673
@property def atexit(self): 'Whether finalizer should be called at exit' info = self._registry.get(self) return (bool(info) and info.atexit)
Whether finalizer should be called at exit
numba/utils.py
atexit
meawoppl/numba
1
python
@property def atexit(self): info = self._registry.get(self) return (bool(info) and info.atexit)
@property def atexit(self): info = self._registry.get(self) return (bool(info) and info.atexit)<|docstring|>Whether finalizer should be called at exit<|endoftext|>
0bfe30e2beb8adb5e5efff7f5250e8851d30a043508559d7a42c40f30e7ea224
def chose_norm(norm_type, channel_size): 'The input of normlization will be (M, C, K), where M is batch size,\n C is channel size and K is sequence length.\n ' if (norm_type == 'gLN'): return GlobalLayerNorm(channel_size) elif (norm_type == 'cLN'): return ChannelwiseLayerNorm(channel_size) else: return nn.BatchNorm1d(channel_size)
The input of normlization will be (M, C, K), where M is batch size, C is channel size and K is sequence length.
src/models/conv_tasnet.py
chose_norm
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def chose_norm(norm_type, channel_size): 'The input of normlization will be (M, C, K), where M is batch size,\n C is channel size and K is sequence length.\n ' if (norm_type == 'gLN'): return GlobalLayerNorm(channel_size) elif (norm_type == 'cLN'): return ChannelwiseLayerNorm(channel_size) else: return nn.BatchNorm1d(channel_size)
def chose_norm(norm_type, channel_size): 'The input of normlization will be (M, C, K), where M is batch size,\n C is channel size and K is sequence length.\n ' if (norm_type == 'gLN'): return GlobalLayerNorm(channel_size) elif (norm_type == 'cLN'): return ChannelwiseLayerNorm(channel_size) else: return nn.BatchNorm1d(channel_size)<|docstring|>The input of normlization will be (M, C, K), where M is batch size, C is channel size and K is sequence length.<|endoftext|>
4916e3d65027f7bcf53776c6d218c0c908dbf54aaece0ead41a0b02cd8ebb1f3
def overlap_and_add(signal, frame_step): "Reconstructs a signal from a framed representation.\n\n Adds potentially overlapping frames of a signal with shape\n `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`.\n The resulting tensor has shape `[..., output_size]` where\n\n output_size = (frames - 1) * frame_step + frame_length\n\n Args:\n signal: A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2.\n frame_step: An integer denoting overlap offsets. Must be less than or equal to frame_length.\n\n Returns:\n A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions.\n output_size = (frames - 1) * frame_step + frame_length\n\n Based on https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/contrib/signal/python/ops/reconstruction_ops.py\n " outer_dimensions = signal.size()[:(- 2)] (frames, frame_length) = signal.size()[(- 2):] subframe_length = math.gcd(frame_length, frame_step) subframe_step = (frame_step // subframe_length) subframes_per_frame = (frame_length // subframe_length) output_size = ((frame_step * (frames - 1)) + frame_length) output_subframes = (output_size // subframe_length) subframe_signal = signal.view(*outer_dimensions, (- 1), subframe_length) frame = torch.arange(0, output_subframes).unfold(0, subframes_per_frame, subframe_step) frame = signal.new_tensor(frame).long() frame = frame.contiguous().view((- 1)) result = signal.new_zeros(*outer_dimensions, output_subframes, subframe_length) result.index_add_((- 2), frame, subframe_signal) result = result.view(*outer_dimensions, (- 1)) return result
Reconstructs a signal from a framed representation. Adds potentially overlapping frames of a signal with shape `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`. The resulting tensor has shape `[..., output_size]` where output_size = (frames - 1) * frame_step + frame_length Args: signal: A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2. frame_step: An integer denoting overlap offsets. Must be less than or equal to frame_length. Returns: A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions. output_size = (frames - 1) * frame_step + frame_length Based on https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/contrib/signal/python/ops/reconstruction_ops.py
src/models/conv_tasnet.py
overlap_and_add
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def overlap_and_add(signal, frame_step): "Reconstructs a signal from a framed representation.\n\n Adds potentially overlapping frames of a signal with shape\n `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`.\n The resulting tensor has shape `[..., output_size]` where\n\n output_size = (frames - 1) * frame_step + frame_length\n\n Args:\n signal: A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2.\n frame_step: An integer denoting overlap offsets. Must be less than or equal to frame_length.\n\n Returns:\n A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions.\n output_size = (frames - 1) * frame_step + frame_length\n\n Based on https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/contrib/signal/python/ops/reconstruction_ops.py\n " outer_dimensions = signal.size()[:(- 2)] (frames, frame_length) = signal.size()[(- 2):] subframe_length = math.gcd(frame_length, frame_step) subframe_step = (frame_step // subframe_length) subframes_per_frame = (frame_length // subframe_length) output_size = ((frame_step * (frames - 1)) + frame_length) output_subframes = (output_size // subframe_length) subframe_signal = signal.view(*outer_dimensions, (- 1), subframe_length) frame = torch.arange(0, output_subframes).unfold(0, subframes_per_frame, subframe_step) frame = signal.new_tensor(frame).long() frame = frame.contiguous().view((- 1)) result = signal.new_zeros(*outer_dimensions, output_subframes, subframe_length) result.index_add_((- 2), frame, subframe_signal) result = result.view(*outer_dimensions, (- 1)) return result
def overlap_and_add(signal, frame_step): "Reconstructs a signal from a framed representation.\n\n Adds potentially overlapping frames of a signal with shape\n `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`.\n The resulting tensor has shape `[..., output_size]` where\n\n output_size = (frames - 1) * frame_step + frame_length\n\n Args:\n signal: A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2.\n frame_step: An integer denoting overlap offsets. Must be less than or equal to frame_length.\n\n Returns:\n A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions.\n output_size = (frames - 1) * frame_step + frame_length\n\n Based on https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/contrib/signal/python/ops/reconstruction_ops.py\n " outer_dimensions = signal.size()[:(- 2)] (frames, frame_length) = signal.size()[(- 2):] subframe_length = math.gcd(frame_length, frame_step) subframe_step = (frame_step // subframe_length) subframes_per_frame = (frame_length // subframe_length) output_size = ((frame_step * (frames - 1)) + frame_length) output_subframes = (output_size // subframe_length) subframe_signal = signal.view(*outer_dimensions, (- 1), subframe_length) frame = torch.arange(0, output_subframes).unfold(0, subframes_per_frame, subframe_step) frame = signal.new_tensor(frame).long() frame = frame.contiguous().view((- 1)) result = signal.new_zeros(*outer_dimensions, output_subframes, subframe_length) result.index_add_((- 2), frame, subframe_signal) result = result.view(*outer_dimensions, (- 1)) return result<|docstring|>Reconstructs a signal from a framed representation. Adds potentially overlapping frames of a signal with shape `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`. The resulting tensor has shape `[..., output_size]` where output_size = (frames - 1) * frame_step + frame_length Args: signal: A [..., frames, frame_length] Tensor. All dimensions may be unknown, and rank must be at least 2. frame_step: An integer denoting overlap offsets. Must be less than or equal to frame_length. Returns: A Tensor with shape [..., output_size] containing the overlap-added frames of signal's inner-most two dimensions. output_size = (frames - 1) * frame_step + frame_length Based on https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/contrib/signal/python/ops/reconstruction_ops.py<|endoftext|>
970cd622805b260f127db48d0f4c4b655f528204bc3c2261093126670de8b9dd
def __init__(self, N, L, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', T=None, dropout_prob=0.2): '\n Args:\n N: Number of filters in autoencoder\n L: Length of the filters (in samples)\n B: Number of channels in bottleneck 1 × 1-conv block\n H: Number of channels in convolutional blocks\n P: Kernel size in convolutional blocks\n X: Number of convolutional blocks in each repeat\n R: Number of repeats\n C: Number of output classes\n norm_type: BN, gLN, cLN\n causal: causal or non-causal\n mask_nonlinear: use which non-linear function to generate mask\n T: number of input samples\n ' super(ConvTasNet, self).__init__() (self.N, self.L, self.B, self.H, self.P, self.X, self.R, self.C, self.T) = (N, L, B, H, P, X, R, C, T) self.norm_type = norm_type self.causal = causal self.mask_nonlinear = mask_nonlinear self.encoder = Encoder(L, N) self.separator = TemporalConvNet(N, B, H, P, X, R, C, norm_type, causal, mask_nonlinear) self.decoder = Decoder(N, L, C, T, dropout_prob) for p in self.parameters(): if (p.dim() > 1): nn.init.xavier_normal_(p)
Args: N: Number of filters in autoencoder L: Length of the filters (in samples) B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of output classes norm_type: BN, gLN, cLN causal: causal or non-causal mask_nonlinear: use which non-linear function to generate mask T: number of input samples
src/models/conv_tasnet.py
__init__
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def __init__(self, N, L, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', T=None, dropout_prob=0.2): '\n Args:\n N: Number of filters in autoencoder\n L: Length of the filters (in samples)\n B: Number of channels in bottleneck 1 × 1-conv block\n H: Number of channels in convolutional blocks\n P: Kernel size in convolutional blocks\n X: Number of convolutional blocks in each repeat\n R: Number of repeats\n C: Number of output classes\n norm_type: BN, gLN, cLN\n causal: causal or non-causal\n mask_nonlinear: use which non-linear function to generate mask\n T: number of input samples\n ' super(ConvTasNet, self).__init__() (self.N, self.L, self.B, self.H, self.P, self.X, self.R, self.C, self.T) = (N, L, B, H, P, X, R, C, T) self.norm_type = norm_type self.causal = causal self.mask_nonlinear = mask_nonlinear self.encoder = Encoder(L, N) self.separator = TemporalConvNet(N, B, H, P, X, R, C, norm_type, causal, mask_nonlinear) self.decoder = Decoder(N, L, C, T, dropout_prob) for p in self.parameters(): if (p.dim() > 1): nn.init.xavier_normal_(p)
def __init__(self, N, L, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', T=None, dropout_prob=0.2): '\n Args:\n N: Number of filters in autoencoder\n L: Length of the filters (in samples)\n B: Number of channels in bottleneck 1 × 1-conv block\n H: Number of channels in convolutional blocks\n P: Kernel size in convolutional blocks\n X: Number of convolutional blocks in each repeat\n R: Number of repeats\n C: Number of output classes\n norm_type: BN, gLN, cLN\n causal: causal or non-causal\n mask_nonlinear: use which non-linear function to generate mask\n T: number of input samples\n ' super(ConvTasNet, self).__init__() (self.N, self.L, self.B, self.H, self.P, self.X, self.R, self.C, self.T) = (N, L, B, H, P, X, R, C, T) self.norm_type = norm_type self.causal = causal self.mask_nonlinear = mask_nonlinear self.encoder = Encoder(L, N) self.separator = TemporalConvNet(N, B, H, P, X, R, C, norm_type, causal, mask_nonlinear) self.decoder = Decoder(N, L, C, T, dropout_prob) for p in self.parameters(): if (p.dim() > 1): nn.init.xavier_normal_(p)<|docstring|>Args: N: Number of filters in autoencoder L: Length of the filters (in samples) B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of output classes norm_type: BN, gLN, cLN causal: causal or non-causal mask_nonlinear: use which non-linear function to generate mask T: number of input samples<|endoftext|>
1ad248abefdbc1181429b9bcd8474c03558833fbf2fb9cd93dedeaf41eb2c1b0
def forward(self, mixture): '\n Args:\n mixture: [M, T], M is batch size, T is #samples\n Returns:\n est_source: [M, C, T]\n ' mixture_w = self.encoder(mixture) est_mask = self.separator(mixture_w) est_source = self.decoder(mixture_w, est_mask, multiply=True) return est_source
Args: mixture: [M, T], M is batch size, T is #samples Returns: est_source: [M, C, T]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, mixture): '\n Args:\n mixture: [M, T], M is batch size, T is #samples\n Returns:\n est_source: [M, C, T]\n ' mixture_w = self.encoder(mixture) est_mask = self.separator(mixture_w) est_source = self.decoder(mixture_w, est_mask, multiply=True) return est_source
def forward(self, mixture): '\n Args:\n mixture: [M, T], M is batch size, T is #samples\n Returns:\n est_source: [M, C, T]\n ' mixture_w = self.encoder(mixture) est_mask = self.separator(mixture_w) est_source = self.decoder(mixture_w, est_mask, multiply=True) return est_source<|docstring|>Args: mixture: [M, T], M is batch size, T is #samples Returns: est_source: [M, C, T]<|endoftext|>
8c87859e16485ca8fe8845f13640612031cfef566cae3abcfb8376aa934719c5
def forward(self, mixture): '\n Args:\n mixture: [M, T], M is batch size, T is #samples\n Returns:\n mixture_w: [M, N, K], where K = (T-L)/(L/2)+1 = 2T/L-1\n ' mixture = torch.unsqueeze(mixture, 1) mixture_w = F.relu(self.conv1d_U(mixture)) return mixture_w
Args: mixture: [M, T], M is batch size, T is #samples Returns: mixture_w: [M, N, K], where K = (T-L)/(L/2)+1 = 2T/L-1
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, mixture): '\n Args:\n mixture: [M, T], M is batch size, T is #samples\n Returns:\n mixture_w: [M, N, K], where K = (T-L)/(L/2)+1 = 2T/L-1\n ' mixture = torch.unsqueeze(mixture, 1) mixture_w = F.relu(self.conv1d_U(mixture)) return mixture_w
def forward(self, mixture): '\n Args:\n mixture: [M, T], M is batch size, T is #samples\n Returns:\n mixture_w: [M, N, K], where K = (T-L)/(L/2)+1 = 2T/L-1\n ' mixture = torch.unsqueeze(mixture, 1) mixture_w = F.relu(self.conv1d_U(mixture)) return mixture_w<|docstring|>Args: mixture: [M, T], M is batch size, T is #samples Returns: mixture_w: [M, N, K], where K = (T-L)/(L/2)+1 = 2T/L-1<|endoftext|>
020ee9ef54771afd428fb632e9b672f23448c9bdd6144842b1a129da86c93a25
def forward(self, mixture_w, est_mask, multiply: bool): '\n Args:\n mixture_w: [M, N, K]\n est_mask: [M, C, N, K]\n Returns:\n est_source: [M, C, T]\n ' if multiply: source_w = (torch.unsqueeze(mixture_w, 1) * est_mask) else: source_w = est_mask source_w = torch.transpose(source_w, 2, 3) est_source = self.basis_signals(source_w) est_source = self.dropout(est_source) if (self.K is None): est_mean = est_source.mean(2) prediction = est_mean.view((- 1), (self.C * self.L)) else: prediction = est_source.view((- 1), ((self.C * self.L) * self.K)) prediction = F.relu(self.fc1(prediction)) prediction = self.dropout(prediction) prediction = self.fc2(prediction) return prediction
Args: mixture_w: [M, N, K] est_mask: [M, C, N, K] Returns: est_source: [M, C, T]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, mixture_w, est_mask, multiply: bool): '\n Args:\n mixture_w: [M, N, K]\n est_mask: [M, C, N, K]\n Returns:\n est_source: [M, C, T]\n ' if multiply: source_w = (torch.unsqueeze(mixture_w, 1) * est_mask) else: source_w = est_mask source_w = torch.transpose(source_w, 2, 3) est_source = self.basis_signals(source_w) est_source = self.dropout(est_source) if (self.K is None): est_mean = est_source.mean(2) prediction = est_mean.view((- 1), (self.C * self.L)) else: prediction = est_source.view((- 1), ((self.C * self.L) * self.K)) prediction = F.relu(self.fc1(prediction)) prediction = self.dropout(prediction) prediction = self.fc2(prediction) return prediction
def forward(self, mixture_w, est_mask, multiply: bool): '\n Args:\n mixture_w: [M, N, K]\n est_mask: [M, C, N, K]\n Returns:\n est_source: [M, C, T]\n ' if multiply: source_w = (torch.unsqueeze(mixture_w, 1) * est_mask) else: source_w = est_mask source_w = torch.transpose(source_w, 2, 3) est_source = self.basis_signals(source_w) est_source = self.dropout(est_source) if (self.K is None): est_mean = est_source.mean(2) prediction = est_mean.view((- 1), (self.C * self.L)) else: prediction = est_source.view((- 1), ((self.C * self.L) * self.K)) prediction = F.relu(self.fc1(prediction)) prediction = self.dropout(prediction) prediction = self.fc2(prediction) return prediction<|docstring|>Args: mixture_w: [M, N, K] est_mask: [M, C, N, K] Returns: est_source: [M, C, T]<|endoftext|>
b3c1e551c4efe2a529f15b9656a58c37d092f5656867a771640c508c1529d2f0
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): '\n Args:\n N: Number of filters in autoencoder\n B: Number of channels in bottleneck 1 × 1-conv block\n H: Number of channels in convolutional blocks\n P: Kernel size in convolutional blocks\n X: Number of convolutional blocks in each repeat\n R: Number of repeats\n C: Number of speakers\n norm_type: BN, gLN, cLN\n causal: causal or non-causal\n mask_nonlinear: use which non-linear function to generate mask\n ' super(TemporalConvNet, self).__init__() self.C = C self.mask_nonlinear = mask_nonlinear layer_norm = ChannelwiseLayerNorm(N) bottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False) repeats = [] for r in range(R): blocks = [] for x in range(X): dilation = (2 ** x) padding = (((P - 1) * dilation) if causal else (((P - 1) * dilation) // 2)) blocks += [TemporalBlock(B, H, P, stride=1, padding=padding, dilation=dilation, norm_type=norm_type, causal=causal)] repeats += [nn.Sequential(*blocks)] temporal_conv_net = nn.Sequential(*repeats) mask_conv1x1 = nn.Conv1d(B, (C * N), 1, bias=False) self.network = nn.Sequential(layer_norm, bottleneck_conv1x1, temporal_conv_net, mask_conv1x1)
Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of speakers norm_type: BN, gLN, cLN causal: causal or non-causal mask_nonlinear: use which non-linear function to generate mask
src/models/conv_tasnet.py
__init__
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): '\n Args:\n N: Number of filters in autoencoder\n B: Number of channels in bottleneck 1 × 1-conv block\n H: Number of channels in convolutional blocks\n P: Kernel size in convolutional blocks\n X: Number of convolutional blocks in each repeat\n R: Number of repeats\n C: Number of speakers\n norm_type: BN, gLN, cLN\n causal: causal or non-causal\n mask_nonlinear: use which non-linear function to generate mask\n ' super(TemporalConvNet, self).__init__() self.C = C self.mask_nonlinear = mask_nonlinear layer_norm = ChannelwiseLayerNorm(N) bottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False) repeats = [] for r in range(R): blocks = [] for x in range(X): dilation = (2 ** x) padding = (((P - 1) * dilation) if causal else (((P - 1) * dilation) // 2)) blocks += [TemporalBlock(B, H, P, stride=1, padding=padding, dilation=dilation, norm_type=norm_type, causal=causal)] repeats += [nn.Sequential(*blocks)] temporal_conv_net = nn.Sequential(*repeats) mask_conv1x1 = nn.Conv1d(B, (C * N), 1, bias=False) self.network = nn.Sequential(layer_norm, bottleneck_conv1x1, temporal_conv_net, mask_conv1x1)
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): '\n Args:\n N: Number of filters in autoencoder\n B: Number of channels in bottleneck 1 × 1-conv block\n H: Number of channels in convolutional blocks\n P: Kernel size in convolutional blocks\n X: Number of convolutional blocks in each repeat\n R: Number of repeats\n C: Number of speakers\n norm_type: BN, gLN, cLN\n causal: causal or non-causal\n mask_nonlinear: use which non-linear function to generate mask\n ' super(TemporalConvNet, self).__init__() self.C = C self.mask_nonlinear = mask_nonlinear layer_norm = ChannelwiseLayerNorm(N) bottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False) repeats = [] for r in range(R): blocks = [] for x in range(X): dilation = (2 ** x) padding = (((P - 1) * dilation) if causal else (((P - 1) * dilation) // 2)) blocks += [TemporalBlock(B, H, P, stride=1, padding=padding, dilation=dilation, norm_type=norm_type, causal=causal)] repeats += [nn.Sequential(*blocks)] temporal_conv_net = nn.Sequential(*repeats) mask_conv1x1 = nn.Conv1d(B, (C * N), 1, bias=False) self.network = nn.Sequential(layer_norm, bottleneck_conv1x1, temporal_conv_net, mask_conv1x1)<|docstring|>Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of speakers norm_type: BN, gLN, cLN causal: causal or non-causal mask_nonlinear: use which non-linear function to generate mask<|endoftext|>
5a615f7cc3f3c079a46b120974b464db04c75993460d2188951677d2225c154c
def forward(self, mixture_w): '\n Keep this API same with TasNet\n Args:\n mixture_w: [M, N, K], M is batch size\n returns:\n est_mask: [M, C, N, K]\n ' (M, N, K) = mixture_w.size() score = self.network(mixture_w) score = score.view(M, self.C, N, K) if (self.mask_nonlinear == 'softmax'): est_mask = F.softmax(score, dim=1) elif (self.mask_nonlinear == 'relu'): est_mask = F.relu(score) else: raise ValueError('Unsupported mask non-linear function') return est_mask
Keep this API same with TasNet Args: mixture_w: [M, N, K], M is batch size returns: est_mask: [M, C, N, K]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, mixture_w): '\n Keep this API same with TasNet\n Args:\n mixture_w: [M, N, K], M is batch size\n returns:\n est_mask: [M, C, N, K]\n ' (M, N, K) = mixture_w.size() score = self.network(mixture_w) score = score.view(M, self.C, N, K) if (self.mask_nonlinear == 'softmax'): est_mask = F.softmax(score, dim=1) elif (self.mask_nonlinear == 'relu'): est_mask = F.relu(score) else: raise ValueError('Unsupported mask non-linear function') return est_mask
def forward(self, mixture_w): '\n Keep this API same with TasNet\n Args:\n mixture_w: [M, N, K], M is batch size\n returns:\n est_mask: [M, C, N, K]\n ' (M, N, K) = mixture_w.size() score = self.network(mixture_w) score = score.view(M, self.C, N, K) if (self.mask_nonlinear == 'softmax'): est_mask = F.softmax(score, dim=1) elif (self.mask_nonlinear == 'relu'): est_mask = F.relu(score) else: raise ValueError('Unsupported mask non-linear function') return est_mask<|docstring|>Keep this API same with TasNet Args: mixture_w: [M, N, K], M is batch size returns: est_mask: [M, C, N, K]<|endoftext|>
66a66cdc3b03b865bde590c0a21729e729b2f3e9631ce06062a40ae173fe82ba
def forward(self, x): '\n Args:\n x: [M, B, K]\n Returns:\n [M, B, K]\n ' residual = x out = self.net(x) return (out + residual)
Args: x: [M, B, K] Returns: [M, B, K]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, x): '\n Args:\n x: [M, B, K]\n Returns:\n [M, B, K]\n ' residual = x out = self.net(x) return (out + residual)
def forward(self, x): '\n Args:\n x: [M, B, K]\n Returns:\n [M, B, K]\n ' residual = x out = self.net(x) return (out + residual)<|docstring|>Args: x: [M, B, K] Returns: [M, B, K]<|endoftext|>
202325f0867a1531b6a8653f48c7c997ce76966e9fe378e7a890fc88b240853d
def forward(self, x): '\n Args:\n x: [M, H, K]\n Returns:\n result: [M, B, K]\n ' return self.net(x)
Args: x: [M, H, K] Returns: result: [M, B, K]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, x): '\n Args:\n x: [M, H, K]\n Returns:\n result: [M, B, K]\n ' return self.net(x)
def forward(self, x): '\n Args:\n x: [M, H, K]\n Returns:\n result: [M, B, K]\n ' return self.net(x)<|docstring|>Args: x: [M, H, K] Returns: result: [M, B, K]<|endoftext|>
5b76d7455b75415fdf90c6663495f5ce2158ec75f2b380233f2b9b53ad5c379c
def forward(self, x): '\n Args:\n x: [M, H, Kpad]\n Returns:\n [M, H, K]\n ' return x[(:, :, :(- self.chomp_size))].contiguous()
Args: x: [M, H, Kpad] Returns: [M, H, K]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, x): '\n Args:\n x: [M, H, Kpad]\n Returns:\n [M, H, K]\n ' return x[(:, :, :(- self.chomp_size))].contiguous()
def forward(self, x): '\n Args:\n x: [M, H, Kpad]\n Returns:\n [M, H, K]\n ' return x[(:, :, :(- self.chomp_size))].contiguous()<|docstring|>Args: x: [M, H, Kpad] Returns: [M, H, K]<|endoftext|>
abc3fa19fa330e101d53c3e4cc9359baa2e4154b2221cb360a7d37a2e4c066ff
def forward(self, y): '\n Args:\n y: [M, N, K], M is batch size, N is channel size, K is length\n Returns:\n cLN_y: [M, N, K]\n ' mean = torch.mean(y, dim=1, keepdim=True) var = torch.var(y, dim=1, keepdim=True, unbiased=False) cLN_y = (((self.gamma * (y - mean)) / torch.pow((var + EPS), 0.5)) + self.beta) return cLN_y
Args: y: [M, N, K], M is batch size, N is channel size, K is length Returns: cLN_y: [M, N, K]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, y): '\n Args:\n y: [M, N, K], M is batch size, N is channel size, K is length\n Returns:\n cLN_y: [M, N, K]\n ' mean = torch.mean(y, dim=1, keepdim=True) var = torch.var(y, dim=1, keepdim=True, unbiased=False) cLN_y = (((self.gamma * (y - mean)) / torch.pow((var + EPS), 0.5)) + self.beta) return cLN_y
def forward(self, y): '\n Args:\n y: [M, N, K], M is batch size, N is channel size, K is length\n Returns:\n cLN_y: [M, N, K]\n ' mean = torch.mean(y, dim=1, keepdim=True) var = torch.var(y, dim=1, keepdim=True, unbiased=False) cLN_y = (((self.gamma * (y - mean)) / torch.pow((var + EPS), 0.5)) + self.beta) return cLN_y<|docstring|>Args: y: [M, N, K], M is batch size, N is channel size, K is length Returns: cLN_y: [M, N, K]<|endoftext|>
55d9d84b06e9498f1c1d0fc31c4c13093eec5c1073eaedf73f9eae5db22d1a4d
def forward(self, y): '\n Args:\n y: [M, N, K], M is batch size, N is channel size, K is length\n Returns:\n gLN_y: [M, N, K]\n ' mean = y.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True) var = torch.pow((y - mean), 2).mean(dim=1, keepdim=True).mean(dim=2, keepdim=True) gLN_y = (((self.gamma * (y - mean)) / torch.pow((var + EPS), 0.5)) + self.beta) return gLN_y
Args: y: [M, N, K], M is batch size, N is channel size, K is length Returns: gLN_y: [M, N, K]
src/models/conv_tasnet.py
forward
ThomasRigoni7/Audio-emotion-recognition-RAVDESS
5
python
def forward(self, y): '\n Args:\n y: [M, N, K], M is batch size, N is channel size, K is length\n Returns:\n gLN_y: [M, N, K]\n ' mean = y.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True) var = torch.pow((y - mean), 2).mean(dim=1, keepdim=True).mean(dim=2, keepdim=True) gLN_y = (((self.gamma * (y - mean)) / torch.pow((var + EPS), 0.5)) + self.beta) return gLN_y
def forward(self, y): '\n Args:\n y: [M, N, K], M is batch size, N is channel size, K is length\n Returns:\n gLN_y: [M, N, K]\n ' mean = y.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True) var = torch.pow((y - mean), 2).mean(dim=1, keepdim=True).mean(dim=2, keepdim=True) gLN_y = (((self.gamma * (y - mean)) / torch.pow((var + EPS), 0.5)) + self.beta) return gLN_y<|docstring|>Args: y: [M, N, K], M is batch size, N is channel size, K is length Returns: gLN_y: [M, N, K]<|endoftext|>
bdf80e5ad5c77d4eff9fc23f885c9d848c12fdb08517448fd5fb3ea4a7514c31
@classmethod def create(klass, tasklist_template, parent, **checkpoint_kwargs): 'Instantiate checkpoints and tasks based on a tasklist template.' allowed_kwargs = ['organization_id', 'program_label', 'project_id', 'cohort_label', 'project_cohort_id', 'survey_id'] if [k for k in checkpoint_kwargs.keys() if (k not in allowed_kwargs)]: raise Exception('Invalids kwargs: {}'.format(checkpoint_kwargs)) checkpoint_kwargs['parent_id'] = parent.uid task_kwargs = {} parent_kind = DatastoreModel.get_kind(parent) if (parent_kind == 'Organization'): checkpoint_kwargs['organization_id'] = parent.uid elif (parent_kind == 'Project'): checkpoint_kwargs['project_id'] = parent.uid task_kwargs['program_label'] = parent.program_label elif (parent_kind == 'Survey'): checkpoint_kwargs['survey_id'] = parent.uid checkpoint_kwargs['project_cohort_id'] = parent.project_cohort_id task_kwargs['program_label'] = parent.program_label for (i, checkpoint_tmpl) in enumerate(tasklist_template): checkpoint_tmpl['ordinal'] = (i + 1) checkpoints = [] for checkpoint_tmpl in tasklist_template: merged_params = dict(checkpoint_tmpl.copy(), **checkpoint_kwargs) checkpoints.append(Checkpoint.create(**merged_params)) tasks = [] task_ord = 1 for (i, checkpoint_tmpl) in enumerate(tasklist_template): checkpoint = checkpoints[i] checkpoint_task_ids = [] for task_tmpl in checkpoint_tmpl['tasks']: kwargs = task_kwargs.copy() kwargs.update(task_tmpl.get('initial_values', {})) task = Task.create(task_tmpl['label'], task_ord, checkpoint.uid, parent=parent, **kwargs) tasks.append(task) checkpoint_task_ids.append(task.uid) task_ord += 1 checkpoint.task_ids = json.dumps(checkpoint_task_ids) return Tasklist(parent, checkpoints, tasks)
Instantiate checkpoints and tasks based on a tasklist template.
app/model/tasklist.py
create
Stanford-PERTS/neptune
0
python
@classmethod def create(klass, tasklist_template, parent, **checkpoint_kwargs): allowed_kwargs = ['organization_id', 'program_label', 'project_id', 'cohort_label', 'project_cohort_id', 'survey_id'] if [k for k in checkpoint_kwargs.keys() if (k not in allowed_kwargs)]: raise Exception('Invalids kwargs: {}'.format(checkpoint_kwargs)) checkpoint_kwargs['parent_id'] = parent.uid task_kwargs = {} parent_kind = DatastoreModel.get_kind(parent) if (parent_kind == 'Organization'): checkpoint_kwargs['organization_id'] = parent.uid elif (parent_kind == 'Project'): checkpoint_kwargs['project_id'] = parent.uid task_kwargs['program_label'] = parent.program_label elif (parent_kind == 'Survey'): checkpoint_kwargs['survey_id'] = parent.uid checkpoint_kwargs['project_cohort_id'] = parent.project_cohort_id task_kwargs['program_label'] = parent.program_label for (i, checkpoint_tmpl) in enumerate(tasklist_template): checkpoint_tmpl['ordinal'] = (i + 1) checkpoints = [] for checkpoint_tmpl in tasklist_template: merged_params = dict(checkpoint_tmpl.copy(), **checkpoint_kwargs) checkpoints.append(Checkpoint.create(**merged_params)) tasks = [] task_ord = 1 for (i, checkpoint_tmpl) in enumerate(tasklist_template): checkpoint = checkpoints[i] checkpoint_task_ids = [] for task_tmpl in checkpoint_tmpl['tasks']: kwargs = task_kwargs.copy() kwargs.update(task_tmpl.get('initial_values', {})) task = Task.create(task_tmpl['label'], task_ord, checkpoint.uid, parent=parent, **kwargs) tasks.append(task) checkpoint_task_ids.append(task.uid) task_ord += 1 checkpoint.task_ids = json.dumps(checkpoint_task_ids) return Tasklist(parent, checkpoints, tasks)
@classmethod def create(klass, tasklist_template, parent, **checkpoint_kwargs): allowed_kwargs = ['organization_id', 'program_label', 'project_id', 'cohort_label', 'project_cohort_id', 'survey_id'] if [k for k in checkpoint_kwargs.keys() if (k not in allowed_kwargs)]: raise Exception('Invalids kwargs: {}'.format(checkpoint_kwargs)) checkpoint_kwargs['parent_id'] = parent.uid task_kwargs = {} parent_kind = DatastoreModel.get_kind(parent) if (parent_kind == 'Organization'): checkpoint_kwargs['organization_id'] = parent.uid elif (parent_kind == 'Project'): checkpoint_kwargs['project_id'] = parent.uid task_kwargs['program_label'] = parent.program_label elif (parent_kind == 'Survey'): checkpoint_kwargs['survey_id'] = parent.uid checkpoint_kwargs['project_cohort_id'] = parent.project_cohort_id task_kwargs['program_label'] = parent.program_label for (i, checkpoint_tmpl) in enumerate(tasklist_template): checkpoint_tmpl['ordinal'] = (i + 1) checkpoints = [] for checkpoint_tmpl in tasklist_template: merged_params = dict(checkpoint_tmpl.copy(), **checkpoint_kwargs) checkpoints.append(Checkpoint.create(**merged_params)) tasks = [] task_ord = 1 for (i, checkpoint_tmpl) in enumerate(tasklist_template): checkpoint = checkpoints[i] checkpoint_task_ids = [] for task_tmpl in checkpoint_tmpl['tasks']: kwargs = task_kwargs.copy() kwargs.update(task_tmpl.get('initial_values', {})) task = Task.create(task_tmpl['label'], task_ord, checkpoint.uid, parent=parent, **kwargs) tasks.append(task) checkpoint_task_ids.append(task.uid) task_ord += 1 checkpoint.task_ids = json.dumps(checkpoint_task_ids) return Tasklist(parent, checkpoints, tasks)<|docstring|>Instantiate checkpoints and tasks based on a tasklist template.<|endoftext|>
dda7ba61bfab91804b6e4617f316f363c9eda2525c9e9383c44740c9be0d1d9d
def __init__(self, parent, checkpoints=None, tasks=None): 'Checkpoints and tasks provided when called via create(); otherwise\n provides access to parent-related instance methods.' self.parent = parent self.checkpoints = checkpoints self.tasks = tasks
Checkpoints and tasks provided when called via create(); otherwise provides access to parent-related instance methods.
app/model/tasklist.py
__init__
Stanford-PERTS/neptune
0
python
def __init__(self, parent, checkpoints=None, tasks=None): 'Checkpoints and tasks provided when called via create(); otherwise\n provides access to parent-related instance methods.' self.parent = parent self.checkpoints = checkpoints self.tasks = tasks
def __init__(self, parent, checkpoints=None, tasks=None): 'Checkpoints and tasks provided when called via create(); otherwise\n provides access to parent-related instance methods.' self.parent = parent self.checkpoints = checkpoints self.tasks = tasks<|docstring|>Checkpoints and tasks provided when called via create(); otherwise provides access to parent-related instance methods.<|endoftext|>
f71bcbf6b88ed061b1372e7f30572859a2025188db5a4bd364eb3e3508edf35d
def status(self): "Check checkpoint status, returns 'complete' or 'incomplete'." checkpoints = Checkpoint.get(parent_id=self.parent.uid) if all([(c.status == 'complete') for c in checkpoints]): return 'complete' else: return 'incomplete'
Check checkpoint status, returns 'complete' or 'incomplete'.
app/model/tasklist.py
status
Stanford-PERTS/neptune
0
python
def status(self): checkpoints = Checkpoint.get(parent_id=self.parent.uid) if all([(c.status == 'complete') for c in checkpoints]): return 'complete' else: return 'incomplete'
def status(self): checkpoints = Checkpoint.get(parent_id=self.parent.uid) if all([(c.status == 'complete') for c in checkpoints]): return 'complete' else: return 'incomplete'<|docstring|>Check checkpoint status, returns 'complete' or 'incomplete'.<|endoftext|>
431e3b849a23b9550555e805a32b506058c28016b9c5a09f0b59bd92d1c7f344
def open(self, new_owner=None): "Called on any checkpoint update that doesn't close the tasklist.\n\n So far manages creation of TaskReminder entities.\n " if (DatastoreModel.get_kind(self.parent) == 'Organization'): org_id = self.parent.uid else: org_id = self.parent.organization_id owners = User.get(owned_organizations=org_id, n=100) if (new_owner and new_owner.non_admin and (new_owner not in owners)): owners.append(new_owner) trs = [] for owner in owners: num_existing = TaskReminder.count(ancestor=owner, context_id=self.parent.uid) if (num_existing == 0): tr = TaskReminder.create(self.parent, owner) trs.append(tr) ndb.put_multi(trs)
Called on any checkpoint update that doesn't close the tasklist. So far manages creation of TaskReminder entities.
app/model/tasklist.py
open
Stanford-PERTS/neptune
0
python
def open(self, new_owner=None): "Called on any checkpoint update that doesn't close the tasklist.\n\n So far manages creation of TaskReminder entities.\n " if (DatastoreModel.get_kind(self.parent) == 'Organization'): org_id = self.parent.uid else: org_id = self.parent.organization_id owners = User.get(owned_organizations=org_id, n=100) if (new_owner and new_owner.non_admin and (new_owner not in owners)): owners.append(new_owner) trs = [] for owner in owners: num_existing = TaskReminder.count(ancestor=owner, context_id=self.parent.uid) if (num_existing == 0): tr = TaskReminder.create(self.parent, owner) trs.append(tr) ndb.put_multi(trs)
def open(self, new_owner=None): "Called on any checkpoint update that doesn't close the tasklist.\n\n So far manages creation of TaskReminder entities.\n " if (DatastoreModel.get_kind(self.parent) == 'Organization'): org_id = self.parent.uid else: org_id = self.parent.organization_id owners = User.get(owned_organizations=org_id, n=100) if (new_owner and new_owner.non_admin and (new_owner not in owners)): owners.append(new_owner) trs = [] for owner in owners: num_existing = TaskReminder.count(ancestor=owner, context_id=self.parent.uid) if (num_existing == 0): tr = TaskReminder.create(self.parent, owner) trs.append(tr) ndb.put_multi(trs)<|docstring|>Called on any checkpoint update that doesn't close the tasklist. So far manages creation of TaskReminder entities.<|endoftext|>
0df2bd74291f9a4b97462be4aac767720d365bd0ccd0c63b3b5f70e5f1a8ade2
def close(self): 'Cleaning house when a tasklist is done.' TaskReminder.delete_task_reminders(self.parent.uid)
Cleaning house when a tasklist is done.
app/model/tasklist.py
close
Stanford-PERTS/neptune
0
python
def close(self): TaskReminder.delete_task_reminders(self.parent.uid)
def close(self): TaskReminder.delete_task_reminders(self.parent.uid)<|docstring|>Cleaning house when a tasklist is done.<|endoftext|>
37bbefc143cf2b3fa97751ffce75ef81a19828aac53f0e4c0dc3191aa9218f8e
def delete_query_connection(self, search_id): '\n Function to delete search id if the status in Running\n :param search_id: str, search id\n :return: dict\n ' return_obj = dict() try: search_id_length = len(search_id.split(':')) search_id_values = search_id.split(':') if (search_id_length in [2, 3]): (search_session_id, user_session_id) = (search_id_values[0], search_id_values[1]) else: raise SyntaxError(('Invalid search_id format : ' + str(search_id))) response = self.api_client.delete_search(search_session_id, user_session_id) raw_response = response.read() response_code = response.code if (199 < response_code < 300): return_obj['success'] = True elif (response_code in [500, 503]): response_string = raw_response.decode() ErrorResponder.fill_error(return_obj, response_string, ['message']) elif json.loads(raw_response): raw_response = json.loads(raw_response) response_dict = raw_response['errors'][0] ErrorResponder.fill_error(return_obj, response_dict, ['message']) else: raise Exception(raw_response) except Exception as err: return_obj = dict() response_error = err ErrorResponder.fill_error(return_obj, response_error, ['message']) return return_obj
Function to delete search id if the status in Running :param search_id: str, search id :return: dict
stix_shifter_modules/arcsight/stix_transmission/delete_connector.py
delete_query_connection
dennispo/stix-shifter
129
python
def delete_query_connection(self, search_id): '\n Function to delete search id if the status in Running\n :param search_id: str, search id\n :return: dict\n ' return_obj = dict() try: search_id_length = len(search_id.split(':')) search_id_values = search_id.split(':') if (search_id_length in [2, 3]): (search_session_id, user_session_id) = (search_id_values[0], search_id_values[1]) else: raise SyntaxError(('Invalid search_id format : ' + str(search_id))) response = self.api_client.delete_search(search_session_id, user_session_id) raw_response = response.read() response_code = response.code if (199 < response_code < 300): return_obj['success'] = True elif (response_code in [500, 503]): response_string = raw_response.decode() ErrorResponder.fill_error(return_obj, response_string, ['message']) elif json.loads(raw_response): raw_response = json.loads(raw_response) response_dict = raw_response['errors'][0] ErrorResponder.fill_error(return_obj, response_dict, ['message']) else: raise Exception(raw_response) except Exception as err: return_obj = dict() response_error = err ErrorResponder.fill_error(return_obj, response_error, ['message']) return return_obj
def delete_query_connection(self, search_id): '\n Function to delete search id if the status in Running\n :param search_id: str, search id\n :return: dict\n ' return_obj = dict() try: search_id_length = len(search_id.split(':')) search_id_values = search_id.split(':') if (search_id_length in [2, 3]): (search_session_id, user_session_id) = (search_id_values[0], search_id_values[1]) else: raise SyntaxError(('Invalid search_id format : ' + str(search_id))) response = self.api_client.delete_search(search_session_id, user_session_id) raw_response = response.read() response_code = response.code if (199 < response_code < 300): return_obj['success'] = True elif (response_code in [500, 503]): response_string = raw_response.decode() ErrorResponder.fill_error(return_obj, response_string, ['message']) elif json.loads(raw_response): raw_response = json.loads(raw_response) response_dict = raw_response['errors'][0] ErrorResponder.fill_error(return_obj, response_dict, ['message']) else: raise Exception(raw_response) except Exception as err: return_obj = dict() response_error = err ErrorResponder.fill_error(return_obj, response_error, ['message']) return return_obj<|docstring|>Function to delete search id if the status in Running :param search_id: str, search id :return: dict<|endoftext|>
a6d78ccc25721775ff118fcba4cbc12127acf0ce4df18e40f1800b568b2810d1
def forward(self, src, trg, src_mask, trg_mask, src_lengths, trg_lengths): 'Take in and process masked src and target sequences.' (encoder_hidden, encoder_final) = self.encode(src, src_mask, src_lengths) return self.decode(encoder_hidden, encoder_final, src_mask, trg, trg_mask)
Take in and process masked src and target sequences.
models/VanillaEncoderDecoder.py
forward
gamerDecathlete/NormalizingFlowsNMT
0
python
def forward(self, src, trg, src_mask, trg_mask, src_lengths, trg_lengths): (encoder_hidden, encoder_final) = self.encode(src, src_mask, src_lengths) return self.decode(encoder_hidden, encoder_final, src_mask, trg, trg_mask)
def forward(self, src, trg, src_mask, trg_mask, src_lengths, trg_lengths): (encoder_hidden, encoder_final) = self.encode(src, src_mask, src_lengths) return self.decode(encoder_hidden, encoder_final, src_mask, trg, trg_mask)<|docstring|>Take in and process masked src and target sequences.<|endoftext|>
f83736c5b9fcfcc24da1301fcf31281e3aa1b990bf732a2ab8b87fd3f3a23d27
def read_file(input_file, labels): 'Reads a tab separated value file.' df = pd.read_csv(input_file, encoding='utf-8', sep='\t', names=['text', 'label', 'id']) m = df['label'].isin(labels) df = df[m] return df
Reads a tab separated value file.
cbert_dataset.py
read_file
CandyDong/11747-A4
0
python
def read_file(input_file, labels): df = pd.read_csv(input_file, encoding='utf-8', sep='\t', names=['text', 'label', 'id']) m = df['label'].isin(labels) df = df[m] return df
def read_file(input_file, labels): df = pd.read_csv(input_file, encoding='utf-8', sep='\t', names=['text', 'label', 'id']) m = df['label'].isin(labels) df = df[m] return df<|docstring|>Reads a tab separated value file.<|endoftext|>
d72775dd8df6b1cc54f9558e2ada74ba33d337da2f63383749bff1011cc7ba87
def generate_source_files(templates, render_args, output_folder, extra_filters=None): '\n Generate SPM common C code from manifests using given templates\n\n :param templates: Dictionary of template and their auto-generated products\n :param render_args: Dictionary of arguments that should be passed to render\n :param output_folder: Output directory for file generation\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: Path to generated folder containing common generated files\n ' rendered_files = [] templates_dirs = list(set([os.path.dirname(path) for path in templates])) template_files = {os.path.basename(t): t for t in templates} env = Environment(loader=FileSystemLoader(templates_dirs), lstrip_blocks=True, trim_blocks=True, undefined=StrictUndefined) if extra_filters: env.filters.update(extra_filters) for tf in template_files: template = env.get_template(tf) rendered_files.append((templates[template_files[tf]], template.render(**render_args))) rendered_file_dir = os.path.dirname(templates[template_files[tf]]) if (not os.path.exists(rendered_file_dir)): os.makedirs(rendered_file_dir) if (not os.path.exists(output_folder)): os.makedirs(output_folder) for (fname, data) in rendered_files: with open(fname, 'wt') as fh: fh.write(data) return output_folder
Generate SPM common C code from manifests using given templates :param templates: Dictionary of template and their auto-generated products :param render_args: Dictionary of arguments that should be passed to render :param output_folder: Output directory for file generation :param extra_filters: Dictionary of extra filters to use in the rendering process :return: Path to generated folder containing common generated files
tools/psa/generate_mbed_spm_partition_code.py
generate_source_files
fredlee12001/mbed-os
3
python
def generate_source_files(templates, render_args, output_folder, extra_filters=None): '\n Generate SPM common C code from manifests using given templates\n\n :param templates: Dictionary of template and their auto-generated products\n :param render_args: Dictionary of arguments that should be passed to render\n :param output_folder: Output directory for file generation\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: Path to generated folder containing common generated files\n ' rendered_files = [] templates_dirs = list(set([os.path.dirname(path) for path in templates])) template_files = {os.path.basename(t): t for t in templates} env = Environment(loader=FileSystemLoader(templates_dirs), lstrip_blocks=True, trim_blocks=True, undefined=StrictUndefined) if extra_filters: env.filters.update(extra_filters) for tf in template_files: template = env.get_template(tf) rendered_files.append((templates[template_files[tf]], template.render(**render_args))) rendered_file_dir = os.path.dirname(templates[template_files[tf]]) if (not os.path.exists(rendered_file_dir)): os.makedirs(rendered_file_dir) if (not os.path.exists(output_folder)): os.makedirs(output_folder) for (fname, data) in rendered_files: with open(fname, 'wt') as fh: fh.write(data) return output_folder
def generate_source_files(templates, render_args, output_folder, extra_filters=None): '\n Generate SPM common C code from manifests using given templates\n\n :param templates: Dictionary of template and their auto-generated products\n :param render_args: Dictionary of arguments that should be passed to render\n :param output_folder: Output directory for file generation\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: Path to generated folder containing common generated files\n ' rendered_files = [] templates_dirs = list(set([os.path.dirname(path) for path in templates])) template_files = {os.path.basename(t): t for t in templates} env = Environment(loader=FileSystemLoader(templates_dirs), lstrip_blocks=True, trim_blocks=True, undefined=StrictUndefined) if extra_filters: env.filters.update(extra_filters) for tf in template_files: template = env.get_template(tf) rendered_files.append((templates[template_files[tf]], template.render(**render_args))) rendered_file_dir = os.path.dirname(templates[template_files[tf]]) if (not os.path.exists(rendered_file_dir)): os.makedirs(rendered_file_dir) if (not os.path.exists(output_folder)): os.makedirs(output_folder) for (fname, data) in rendered_files: with open(fname, 'wt') as fh: fh.write(data) return output_folder<|docstring|>Generate SPM common C code from manifests using given templates :param templates: Dictionary of template and their auto-generated products :param render_args: Dictionary of arguments that should be passed to render :param output_folder: Output directory for file generation :param extra_filters: Dictionary of extra filters to use in the rendering process :return: Path to generated folder containing common generated files<|endoftext|>
8df075a0ed240d7e492b010ea74d45c6bac4e9c263fd6c84426858a05f38ad71
def generate_partitions_sources(manifest_files, extra_filters=None): '\n Process all the given manifest files and generate C code from them\n\n :param manifest_files: List of manifest files\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: List of paths to the generated files\n ' manifests = [] for manifest_file in manifest_files: manifest = Manifest.from_json(manifest_file) manifests.append(manifest) generated_folders = set() for manifest in manifests: manifest_output_folder = manifest.autogen_folder render_args = {'partition': manifest, 'dependent_partitions': manifest.find_dependencies(manifests), 'script_ver': __version__} manifest_output_folder = generate_source_files(manifest.templates_to_files(MANIFEST_TEMPLATES, TEMPLATES_DIR, manifest_output_folder), render_args, manifest_output_folder, extra_filters=extra_filters) generated_folders.add(manifest_output_folder) return list(generated_folders)
Process all the given manifest files and generate C code from them :param manifest_files: List of manifest files :param extra_filters: Dictionary of extra filters to use in the rendering process :return: List of paths to the generated files
tools/psa/generate_mbed_spm_partition_code.py
generate_partitions_sources
fredlee12001/mbed-os
3
python
def generate_partitions_sources(manifest_files, extra_filters=None): '\n Process all the given manifest files and generate C code from them\n\n :param manifest_files: List of manifest files\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: List of paths to the generated files\n ' manifests = [] for manifest_file in manifest_files: manifest = Manifest.from_json(manifest_file) manifests.append(manifest) generated_folders = set() for manifest in manifests: manifest_output_folder = manifest.autogen_folder render_args = {'partition': manifest, 'dependent_partitions': manifest.find_dependencies(manifests), 'script_ver': __version__} manifest_output_folder = generate_source_files(manifest.templates_to_files(MANIFEST_TEMPLATES, TEMPLATES_DIR, manifest_output_folder), render_args, manifest_output_folder, extra_filters=extra_filters) generated_folders.add(manifest_output_folder) return list(generated_folders)
def generate_partitions_sources(manifest_files, extra_filters=None): '\n Process all the given manifest files and generate C code from them\n\n :param manifest_files: List of manifest files\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: List of paths to the generated files\n ' manifests = [] for manifest_file in manifest_files: manifest = Manifest.from_json(manifest_file) manifests.append(manifest) generated_folders = set() for manifest in manifests: manifest_output_folder = manifest.autogen_folder render_args = {'partition': manifest, 'dependent_partitions': manifest.find_dependencies(manifests), 'script_ver': __version__} manifest_output_folder = generate_source_files(manifest.templates_to_files(MANIFEST_TEMPLATES, TEMPLATES_DIR, manifest_output_folder), render_args, manifest_output_folder, extra_filters=extra_filters) generated_folders.add(manifest_output_folder) return list(generated_folders)<|docstring|>Process all the given manifest files and generate C code from them :param manifest_files: List of manifest files :param extra_filters: Dictionary of extra filters to use in the rendering process :return: List of paths to the generated files<|endoftext|>
631f01afe85d66784e9375c08b3629bab2cb61cf3266354c5bcbe7964c50ef8e
def generate_psa_setup(manifest_files, output_dir, weak_setup, extra_filters=None): '\nProcess all the given manifest files and generate C setup code from them\n :param manifest_files: List of manifest files\n :param output_dir: Output directory for the generated files\n :param weak_setup: Is the functions/data in the setup file weak\n (can be overridden by another setup file)\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: path to the setup generated files\n ' autogen_folder = output_dir templates_dict = {t: path_join(autogen_folder, os.path.relpath(os.path.splitext(t)[0], TEMPLATES_DIR)) for t in COMMON_TEMPLATES} complete_source_list = list(templates_dict.values()) region_list = [] manifests = [] for manifest_file in manifest_files: manifest_obj = Manifest.from_json(manifest_file) manifests.append(manifest_obj) for region in manifest_obj.mmio_regions: region_list.append(region) complete_source_list.extend(list(manifest_obj.templates_to_files(MANIFEST_TEMPLATES, TEMPLATES_DIR, manifest_obj.autogen_folder).values())) validate_partition_manifests(manifests) render_args = {'partitions': manifests, 'regions': region_list, 'region_pair_list': list(itertools.combinations(region_list, 2)), 'weak': weak_setup, 'script_ver': __version__} return generate_source_files(templates_dict, render_args, autogen_folder, extra_filters=extra_filters)
Process all the given manifest files and generate C setup code from them :param manifest_files: List of manifest files :param output_dir: Output directory for the generated files :param weak_setup: Is the functions/data in the setup file weak (can be overridden by another setup file) :param extra_filters: Dictionary of extra filters to use in the rendering process :return: path to the setup generated files
tools/psa/generate_mbed_spm_partition_code.py
generate_psa_setup
fredlee12001/mbed-os
3
python
def generate_psa_setup(manifest_files, output_dir, weak_setup, extra_filters=None): '\nProcess all the given manifest files and generate C setup code from them\n :param manifest_files: List of manifest files\n :param output_dir: Output directory for the generated files\n :param weak_setup: Is the functions/data in the setup file weak\n (can be overridden by another setup file)\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: path to the setup generated files\n ' autogen_folder = output_dir templates_dict = {t: path_join(autogen_folder, os.path.relpath(os.path.splitext(t)[0], TEMPLATES_DIR)) for t in COMMON_TEMPLATES} complete_source_list = list(templates_dict.values()) region_list = [] manifests = [] for manifest_file in manifest_files: manifest_obj = Manifest.from_json(manifest_file) manifests.append(manifest_obj) for region in manifest_obj.mmio_regions: region_list.append(region) complete_source_list.extend(list(manifest_obj.templates_to_files(MANIFEST_TEMPLATES, TEMPLATES_DIR, manifest_obj.autogen_folder).values())) validate_partition_manifests(manifests) render_args = {'partitions': manifests, 'regions': region_list, 'region_pair_list': list(itertools.combinations(region_list, 2)), 'weak': weak_setup, 'script_ver': __version__} return generate_source_files(templates_dict, render_args, autogen_folder, extra_filters=extra_filters)
def generate_psa_setup(manifest_files, output_dir, weak_setup, extra_filters=None): '\nProcess all the given manifest files and generate C setup code from them\n :param manifest_files: List of manifest files\n :param output_dir: Output directory for the generated files\n :param weak_setup: Is the functions/data in the setup file weak\n (can be overridden by another setup file)\n :param extra_filters: Dictionary of extra filters to use in the rendering\n process\n :return: path to the setup generated files\n ' autogen_folder = output_dir templates_dict = {t: path_join(autogen_folder, os.path.relpath(os.path.splitext(t)[0], TEMPLATES_DIR)) for t in COMMON_TEMPLATES} complete_source_list = list(templates_dict.values()) region_list = [] manifests = [] for manifest_file in manifest_files: manifest_obj = Manifest.from_json(manifest_file) manifests.append(manifest_obj) for region in manifest_obj.mmio_regions: region_list.append(region) complete_source_list.extend(list(manifest_obj.templates_to_files(MANIFEST_TEMPLATES, TEMPLATES_DIR, manifest_obj.autogen_folder).values())) validate_partition_manifests(manifests) render_args = {'partitions': manifests, 'regions': region_list, 'region_pair_list': list(itertools.combinations(region_list, 2)), 'weak': weak_setup, 'script_ver': __version__} return generate_source_files(templates_dict, render_args, autogen_folder, extra_filters=extra_filters)<|docstring|>Process all the given manifest files and generate C setup code from them :param manifest_files: List of manifest files :param output_dir: Output directory for the generated files :param weak_setup: Is the functions/data in the setup file weak (can be overridden by another setup file) :param extra_filters: Dictionary of extra filters to use in the rendering process :return: path to the setup generated files<|endoftext|>
d030ac40315e1d6734a2978d389e26feb03f597e1d8fe711b494956d9bc24c7a
def __init__(self): '\n * 初期化\n ' Logger.m_logger = logging.getLogger() logging.basicConfig(level=self.DEBUG, format=self.DEFAULT_FORMAT, datefmt='%H:%M:%S')
* 初期化
Logger.py
__init__
minaka1412/Gadget
0
python
def __init__(self): '\n \n ' Logger.m_logger = logging.getLogger() logging.basicConfig(level=self.DEBUG, format=self.DEFAULT_FORMAT, datefmt='%H:%M:%S')
def __init__(self): '\n \n ' Logger.m_logger = logging.getLogger() logging.basicConfig(level=self.DEBUG, format=self.DEFAULT_FORMAT, datefmt='%H:%M:%S')<|docstring|>* 初期化<|endoftext|>
45917178857b966e2cb0b58f1008b606a2490f56ba57e69086e633e71cc76ea4
@staticmethod def SetLevel(level): '\n * 出力するログのレベルを指定\n * I: Logger.* level 出力するログのレベル\n ' Logger.m_logger.setLevel(level) for handler in Logger.m_handler_dict: handler.setLevel(level)
* 出力するログのレベルを指定 * I: Logger.* level 出力するログのレベル
Logger.py
SetLevel
minaka1412/Gadget
0
python
@staticmethod def SetLevel(level): '\n * 出力するログのレベルを指定\n * I: Logger.* level 出力するログのレベル\n ' Logger.m_logger.setLevel(level) for handler in Logger.m_handler_dict: handler.setLevel(level)
@staticmethod def SetLevel(level): '\n * 出力するログのレベルを指定\n * I: Logger.* level 出力するログのレベル\n ' Logger.m_logger.setLevel(level) for handler in Logger.m_handler_dict: handler.setLevel(level)<|docstring|>* 出力するログのレベルを指定 * I: Logger.* level 出力するログのレベル<|endoftext|>
27a390df61304d728fceaa0a5f6c0f218961dc0a0f4ecfc307c34d3e782e4cc6
@staticmethod def AddOutputFile(path): '\n * 追加出力先のファイルを追加する\n * I: str path 追加出力先のファイルパス\n ' from Directory import Directory from Path import Path parentPath = Path.GetParentPath(path) if (not Directory.Exists(parentPath)): Directory.Create(parentPath) file_handler = logging.FileHandler(path, 'w') file_handler.formatter = logging.Formatter(fmt=Logger.DEFAULT_FORMAT, datefmt='%H:%M:%S') file_handler.level = Logger.DEBUG Logger.m_handler_dict[path] = file_handler Logger.m_logger.addHandler(file_handler)
* 追加出力先のファイルを追加する * I: str path 追加出力先のファイルパス
Logger.py
AddOutputFile
minaka1412/Gadget
0
python
@staticmethod def AddOutputFile(path): '\n * 追加出力先のファイルを追加する\n * I: str path 追加出力先のファイルパス\n ' from Directory import Directory from Path import Path parentPath = Path.GetParentPath(path) if (not Directory.Exists(parentPath)): Directory.Create(parentPath) file_handler = logging.FileHandler(path, 'w') file_handler.formatter = logging.Formatter(fmt=Logger.DEFAULT_FORMAT, datefmt='%H:%M:%S') file_handler.level = Logger.DEBUG Logger.m_handler_dict[path] = file_handler Logger.m_logger.addHandler(file_handler)
@staticmethod def AddOutputFile(path): '\n * 追加出力先のファイルを追加する\n * I: str path 追加出力先のファイルパス\n ' from Directory import Directory from Path import Path parentPath = Path.GetParentPath(path) if (not Directory.Exists(parentPath)): Directory.Create(parentPath) file_handler = logging.FileHandler(path, 'w') file_handler.formatter = logging.Formatter(fmt=Logger.DEFAULT_FORMAT, datefmt='%H:%M:%S') file_handler.level = Logger.DEBUG Logger.m_handler_dict[path] = file_handler Logger.m_logger.addHandler(file_handler)<|docstring|>* 追加出力先のファイルを追加する * I: str path 追加出力先のファイルパス<|endoftext|>
3bf579d5bac4c320e3619788d2b0fc922e29c396b825a6cd07617039b1331372
@staticmethod def CloseOutputFile(path): '\n * 追加出力先のファイルを閉じる\n * I: str path 閉じる追加出力先のファイルパス\n ' file_handler = Logger.m_handler_dict[path] file_handler.close() Logger.m_logger.removeHandler(file_handler) del Logger.m_handler_dict[path]
* 追加出力先のファイルを閉じる * I: str path 閉じる追加出力先のファイルパス
Logger.py
CloseOutputFile
minaka1412/Gadget
0
python
@staticmethod def CloseOutputFile(path): '\n * 追加出力先のファイルを閉じる\n * I: str path 閉じる追加出力先のファイルパス\n ' file_handler = Logger.m_handler_dict[path] file_handler.close() Logger.m_logger.removeHandler(file_handler) del Logger.m_handler_dict[path]
@staticmethod def CloseOutputFile(path): '\n * 追加出力先のファイルを閉じる\n * I: str path 閉じる追加出力先のファイルパス\n ' file_handler = Logger.m_handler_dict[path] file_handler.close() Logger.m_logger.removeHandler(file_handler) del Logger.m_handler_dict[path]<|docstring|>* 追加出力先のファイルを閉じる * I: str path 閉じる追加出力先のファイルパス<|endoftext|>
5673a248e89c9d13d23ee659fc2865b199ed467f08d3aa4bdbdce0f0c247b091
@staticmethod def Log(msg): '\n * レベル DEBUG のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.Debug(msg)
* レベル DEBUG のログを出力 * I: str msg 出力するメッセージ
Logger.py
Log
minaka1412/Gadget
0
python
@staticmethod def Log(msg): '\n * レベル DEBUG のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.Debug(msg)
@staticmethod def Log(msg): '\n * レベル DEBUG のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.Debug(msg)<|docstring|>* レベル DEBUG のログを出力 * I: str msg 出力するメッセージ<|endoftext|>
718f256bf69e9cf5b9702be0145d5efd6f8685d5b6e0aa30d2d07ac0a2ec57ca
@staticmethod def Debug(msg): '\n * レベル DEBUG のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.debug(msg)
* レベル DEBUG のログを出力 * I: str msg 出力するメッセージ
Logger.py
Debug
minaka1412/Gadget
0
python
@staticmethod def Debug(msg): '\n * レベル DEBUG のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.debug(msg)
@staticmethod def Debug(msg): '\n * レベル DEBUG のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.debug(msg)<|docstring|>* レベル DEBUG のログを出力 * I: str msg 出力するメッセージ<|endoftext|>
2bf6f355258ca17862aed7cb496385971713b7fe4904d80430877f8f48ba0024
@staticmethod def Info(msg): '\n * レベル INFO のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.info(msg)
* レベル INFO のログを出力 * I: str msg 出力するメッセージ
Logger.py
Info
minaka1412/Gadget
0
python
@staticmethod def Info(msg): '\n * レベル INFO のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.info(msg)
@staticmethod def Info(msg): '\n * レベル INFO のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.info(msg)<|docstring|>* レベル INFO のログを出力 * I: str msg 出力するメッセージ<|endoftext|>
6628e6dd268f98e0d38e3a38632045ce7fd4054165ae1c6e582f0a87d7611012
@staticmethod def Warning(msg): '\n * レベル WARNING のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.warning(msg)
* レベル WARNING のログを出力 * I: str msg 出力するメッセージ
Logger.py
Warning
minaka1412/Gadget
0
python
@staticmethod def Warning(msg): '\n * レベル WARNING のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.warning(msg)
@staticmethod def Warning(msg): '\n * レベル WARNING のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.warning(msg)<|docstring|>* レベル WARNING のログを出力 * I: str msg 出力するメッセージ<|endoftext|>
414d89ec00b9dfa4926c926e4b768d69acf121f35a767763831bec1c0a5592e7
@staticmethod def Error(msg): '\n * レベル ERROR のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.error(msg)
* レベル ERROR のログを出力 * I: str msg 出力するメッセージ
Logger.py
Error
minaka1412/Gadget
0
python
@staticmethod def Error(msg): '\n * レベル ERROR のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.error(msg)
@staticmethod def Error(msg): '\n * レベル ERROR のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.error(msg)<|docstring|>* レベル ERROR のログを出力 * I: str msg 出力するメッセージ<|endoftext|>
ecedff602f54482094f2efe05657544a622ead3a2e27c7f4e46a07c3ae6ad019
@staticmethod def Critical(msg): '\n * レベル CRITICAL のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.critical(msg)
* レベル CRITICAL のログを出力 * I: str msg 出力するメッセージ
Logger.py
Critical
minaka1412/Gadget
0
python
@staticmethod def Critical(msg): '\n * レベル CRITICAL のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.critical(msg)
@staticmethod def Critical(msg): '\n * レベル CRITICAL のログを出力\n * I: str msg 出力するメッセージ\n ' Logger.m_logger.critical(msg)<|docstring|>* レベル CRITICAL のログを出力 * I: str msg 出力するメッセージ<|endoftext|>
0289265fe737d1a9e7d6c84cf55eeb783b93bed208acf6b6017bfd0c8214e442
def pop(obj, *args, **kwargs): 'Safe pop for list or dict.\n\n Parameters\n ----------\n obj : list or dict\n Input collection.\n elem : default=-1 fot lists, mandatory for dicts\n Element to pop.\n default : optional\n Default value.\n Raise exception if elem does not exist and default not provided.\n\n Returns\n -------\n value :\n Popped value\n\n ' args = list(args) kwargs = dict(kwargs) elem = None elem_known = False default = None default_known = False if (len(args) > 0): elem = args.pop(0) elem_known = True if (len(args) > 0): default = args.pop(0) default_known = True if (len(args) > 0): raise ValueError('Maximum two positional arguments. Got {}'.format((len(args) + 2))) if ('elem' in kwargs.keys()): if elem_known: raise ValueError('Arg `elem` cannot be passed as both a positional and keyword.') else: elem = kwargs.pop('elem') elem_known = True if ('default' in kwargs.keys()): if default_known: raise ValueError('Arg `default` cannot be passed as both a positional and keyword.') else: default = kwargs.pop('default') default_known = True if isinstance(obj, list): if (not elem_known): elem = (- 1) if default_known: try: value = obj.pop(elem) except IndexError: value = default else: value = obj.pop(elem) elif isinstance(obj, dict): if (not elem_known): raise ValueError('Arg `elem` is mandatory for type dict.') if default_known: value = obj.pop(elem, default) else: value = obj.pop(elem) else: raise TypeError('Input object should be a list or dict.') return value
Safe pop for list or dict. Parameters ---------- obj : list or dict Input collection. elem : default=-1 fot lists, mandatory for dicts Element to pop. default : optional Default value. Raise exception if elem does not exist and default not provided. Returns ------- value : Popped value
unik/_utils.py
pop
balbasty/unik
0
python
def pop(obj, *args, **kwargs): 'Safe pop for list or dict.\n\n Parameters\n ----------\n obj : list or dict\n Input collection.\n elem : default=-1 fot lists, mandatory for dicts\n Element to pop.\n default : optional\n Default value.\n Raise exception if elem does not exist and default not provided.\n\n Returns\n -------\n value :\n Popped value\n\n ' args = list(args) kwargs = dict(kwargs) elem = None elem_known = False default = None default_known = False if (len(args) > 0): elem = args.pop(0) elem_known = True if (len(args) > 0): default = args.pop(0) default_known = True if (len(args) > 0): raise ValueError('Maximum two positional arguments. Got {}'.format((len(args) + 2))) if ('elem' in kwargs.keys()): if elem_known: raise ValueError('Arg `elem` cannot be passed as both a positional and keyword.') else: elem = kwargs.pop('elem') elem_known = True if ('default' in kwargs.keys()): if default_known: raise ValueError('Arg `default` cannot be passed as both a positional and keyword.') else: default = kwargs.pop('default') default_known = True if isinstance(obj, list): if (not elem_known): elem = (- 1) if default_known: try: value = obj.pop(elem) except IndexError: value = default else: value = obj.pop(elem) elif isinstance(obj, dict): if (not elem_known): raise ValueError('Arg `elem` is mandatory for type dict.') if default_known: value = obj.pop(elem, default) else: value = obj.pop(elem) else: raise TypeError('Input object should be a list or dict.') return value
def pop(obj, *args, **kwargs): 'Safe pop for list or dict.\n\n Parameters\n ----------\n obj : list or dict\n Input collection.\n elem : default=-1 fot lists, mandatory for dicts\n Element to pop.\n default : optional\n Default value.\n Raise exception if elem does not exist and default not provided.\n\n Returns\n -------\n value :\n Popped value\n\n ' args = list(args) kwargs = dict(kwargs) elem = None elem_known = False default = None default_known = False if (len(args) > 0): elem = args.pop(0) elem_known = True if (len(args) > 0): default = args.pop(0) default_known = True if (len(args) > 0): raise ValueError('Maximum two positional arguments. Got {}'.format((len(args) + 2))) if ('elem' in kwargs.keys()): if elem_known: raise ValueError('Arg `elem` cannot be passed as both a positional and keyword.') else: elem = kwargs.pop('elem') elem_known = True if ('default' in kwargs.keys()): if default_known: raise ValueError('Arg `default` cannot be passed as both a positional and keyword.') else: default = kwargs.pop('default') default_known = True if isinstance(obj, list): if (not elem_known): elem = (- 1) if default_known: try: value = obj.pop(elem) except IndexError: value = default else: value = obj.pop(elem) elif isinstance(obj, dict): if (not elem_known): raise ValueError('Arg `elem` is mandatory for type dict.') if default_known: value = obj.pop(elem, default) else: value = obj.pop(elem) else: raise TypeError('Input object should be a list or dict.') return value<|docstring|>Safe pop for list or dict. Parameters ---------- obj : list or dict Input collection. elem : default=-1 fot lists, mandatory for dicts Element to pop. default : optional Default value. Raise exception if elem does not exist and default not provided. Returns ------- value : Popped value<|endoftext|>
31b08b59f4d8807930be0695050d40dd246bea2f0fcd6fda069ed0f9d372f4e7
def _apply_nested(structure, fn): 'Recursively apply a function to the elements of a list/tuple/dict.' if isinstance(structure, list): return list((_apply_nested(elem, fn) for elem in structure)) elif isinstance(structure, tuple): return tuple((_apply_nested(elem, fn) for elem in structure)) elif isinstance(structure, dict): return dict([(k, _apply_nested(v, fn)) for (k, v) in structure.items()]) else: return fn(structure)
Recursively apply a function to the elements of a list/tuple/dict.
unik/_utils.py
_apply_nested
balbasty/unik
0
python
def _apply_nested(structure, fn): if isinstance(structure, list): return list((_apply_nested(elem, fn) for elem in structure)) elif isinstance(structure, tuple): return tuple((_apply_nested(elem, fn) for elem in structure)) elif isinstance(structure, dict): return dict([(k, _apply_nested(v, fn)) for (k, v) in structure.items()]) else: return fn(structure)
def _apply_nested(structure, fn): if isinstance(structure, list): return list((_apply_nested(elem, fn) for elem in structure)) elif isinstance(structure, tuple): return tuple((_apply_nested(elem, fn) for elem in structure)) elif isinstance(structure, dict): return dict([(k, _apply_nested(v, fn)) for (k, v) in structure.items()]) else: return fn(structure)<|docstring|>Recursively apply a function to the elements of a list/tuple/dict.<|endoftext|>
1aa80dde28760a7cf071a00c9609fea52022c74df6c3388dcc52ff2b542b72e0
def get_template_names(self): '\n Returns a list of template names to be used for the request. Must return\n a list. May not be called if render_to_response is overridden.\n ' domain = Site.objects.get_current().domain if ('west-life' in domain): return ['static_pages/landing_westlife.html'] elif ('pype' in domain): return ['static_pages/landing_pype.html'] return ['static_pages/landing_westlife.html']
Returns a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.
ui/views.py
get_template_names
h2020-westlife-eu/VRE
1
python
def get_template_names(self): '\n Returns a list of template names to be used for the request. Must return\n a list. May not be called if render_to_response is overridden.\n ' domain = Site.objects.get_current().domain if ('west-life' in domain): return ['static_pages/landing_westlife.html'] elif ('pype' in domain): return ['static_pages/landing_pype.html'] return ['static_pages/landing_westlife.html']
def get_template_names(self): '\n Returns a list of template names to be used for the request. Must return\n a list. May not be called if render_to_response is overridden.\n ' domain = Site.objects.get_current().domain if ('west-life' in domain): return ['static_pages/landing_westlife.html'] elif ('pype' in domain): return ['static_pages/landing_pype.html'] return ['static_pages/landing_westlife.html']<|docstring|>Returns a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.<|endoftext|>
d308da20d1b0458a7019a7dd445cd476f991286097eb6e7f34418b5d558946fa
def process(self, message): 'Decode the nmea element in the message body\n ' logging.info('decoding element {}'.format(message)) message.update(self.decoder.safe_decode(message.get('nmea'))) message.add_source(self.source) message.add_uuid() schema_fields = {f['name'] for f in self.schema['fields']} extra_fields = {k: v for (k, v) in message.items() if (k not in schema_fields)} if extra_fields: message = {k: v for (k, v) in message.items() if (k not in extra_fields)} message['extra'] = ujson.dumps(extra_fields) (yield message)
Decode the nmea element in the message body
dataflow/stream_decode/decode.py
process
GlobalFishingWatch/ais-stream
0
python
def process(self, message): '\n ' logging.info('decoding element {}'.format(message)) message.update(self.decoder.safe_decode(message.get('nmea'))) message.add_source(self.source) message.add_uuid() schema_fields = {f['name'] for f in self.schema['fields']} extra_fields = {k: v for (k, v) in message.items() if (k not in schema_fields)} if extra_fields: message = {k: v for (k, v) in message.items() if (k not in extra_fields)} message['extra'] = ujson.dumps(extra_fields) (yield message)
def process(self, message): '\n ' logging.info('decoding element {}'.format(message)) message.update(self.decoder.safe_decode(message.get('nmea'))) message.add_source(self.source) message.add_uuid() schema_fields = {f['name'] for f in self.schema['fields']} extra_fields = {k: v for (k, v) in message.items() if (k not in schema_fields)} if extra_fields: message = {k: v for (k, v) in message.items() if (k not in extra_fields)} message['extra'] = ujson.dumps(extra_fields) (yield message)<|docstring|>Decode the nmea element in the message body<|endoftext|>
55736a4d6c808a43bfd60ba5642a7978158a324a9bc97cb933109f1177e65736
def single_cell_normalize(self): "\n Single cell normalization. Requires expression_matrix to be all numeric, and to be [N x G].\n Executes all preprocessing workflow steps from the preprocessing_workflow list that's set by the\n add_preprocess_step() class function\n " (self.expression_matrix, self.meta_data) = single_cell.filter_genes_for_count(self.expression_matrix, self.meta_data, count_minimum=self.count_minimum) if self.expression_matrix.isnull().values.any(): raise ValueError('NaN values are present prior to normalization in the expression matrix') for (sc_function, sc_kwargs) in self.preprocessing_workflow: sc_kwargs['random_seed'] = self.random_seed (self.expression_matrix, self.meta_data) = sc_function(self.expression_matrix, self.meta_data, **sc_kwargs) if self.expression_matrix.isnull().values.any(): raise ValueError('NaN values have been introduced into the expression matrix by normalization')
Single cell normalization. Requires expression_matrix to be all numeric, and to be [N x G]. Executes all preprocessing workflow steps from the preprocessing_workflow list that's set by the add_preprocess_step() class function
inferelator_ng/single_cell_workflow.py
single_cell_normalize
asistradition/inferelator_ng
1
python
def single_cell_normalize(self): "\n Single cell normalization. Requires expression_matrix to be all numeric, and to be [N x G].\n Executes all preprocessing workflow steps from the preprocessing_workflow list that's set by the\n add_preprocess_step() class function\n " (self.expression_matrix, self.meta_data) = single_cell.filter_genes_for_count(self.expression_matrix, self.meta_data, count_minimum=self.count_minimum) if self.expression_matrix.isnull().values.any(): raise ValueError('NaN values are present prior to normalization in the expression matrix') for (sc_function, sc_kwargs) in self.preprocessing_workflow: sc_kwargs['random_seed'] = self.random_seed (self.expression_matrix, self.meta_data) = sc_function(self.expression_matrix, self.meta_data, **sc_kwargs) if self.expression_matrix.isnull().values.any(): raise ValueError('NaN values have been introduced into the expression matrix by normalization')
def single_cell_normalize(self): "\n Single cell normalization. Requires expression_matrix to be all numeric, and to be [N x G].\n Executes all preprocessing workflow steps from the preprocessing_workflow list that's set by the\n add_preprocess_step() class function\n " (self.expression_matrix, self.meta_data) = single_cell.filter_genes_for_count(self.expression_matrix, self.meta_data, count_minimum=self.count_minimum) if self.expression_matrix.isnull().values.any(): raise ValueError('NaN values are present prior to normalization in the expression matrix') for (sc_function, sc_kwargs) in self.preprocessing_workflow: sc_kwargs['random_seed'] = self.random_seed (self.expression_matrix, self.meta_data) = sc_function(self.expression_matrix, self.meta_data, **sc_kwargs) if self.expression_matrix.isnull().values.any(): raise ValueError('NaN values have been introduced into the expression matrix by normalization')<|docstring|>Single cell normalization. Requires expression_matrix to be all numeric, and to be [N x G]. Executes all preprocessing workflow steps from the preprocessing_workflow list that's set by the add_preprocess_step() class function<|endoftext|>
52a9db094f58b9247746f233fe6bc224134dc8ef2e1e414d95f98f1e5013db97
def compute_activity(self): '\n Compute Transcription Factor Activity\n ' utils.Debug.vprint('Computing Transcription Factor Activity ... ') TFA_calculator = TFA(self.priors_data, self.expression_matrix, self.expression_matrix) self.design = TFA_calculator.compute_transcription_factor_activity() self.response = self.expression_matrix self.expression_matrix = None if self.modify_activity_from_metadata: self.apply_metadata_to_activity()
Compute Transcription Factor Activity
inferelator_ng/single_cell_workflow.py
compute_activity
asistradition/inferelator_ng
1
python
def compute_activity(self): '\n \n ' utils.Debug.vprint('Computing Transcription Factor Activity ... ') TFA_calculator = TFA(self.priors_data, self.expression_matrix, self.expression_matrix) self.design = TFA_calculator.compute_transcription_factor_activity() self.response = self.expression_matrix self.expression_matrix = None if self.modify_activity_from_metadata: self.apply_metadata_to_activity()
def compute_activity(self): '\n \n ' utils.Debug.vprint('Computing Transcription Factor Activity ... ') TFA_calculator = TFA(self.priors_data, self.expression_matrix, self.expression_matrix) self.design = TFA_calculator.compute_transcription_factor_activity() self.response = self.expression_matrix self.expression_matrix = None if self.modify_activity_from_metadata: self.apply_metadata_to_activity()<|docstring|>Compute Transcription Factor Activity<|endoftext|>
136ffd0d78c96d8ec7ef6606ba6600827c0700a3738b6c371788576018b2d4c9
def apply_metadata_to_activity(self): '\n Set design values according to metadata\n :return:\n ' utils.Debug.vprint('Modifying Transcription Factor Activity ... ') self.meta_data[self.metadata_expression_lookup] = self.meta_data[self.metadata_expression_lookup].str.upper() genotypes = self.meta_data[self.metadata_expression_lookup].unique().tolist() if (self.gene_list is not None): genes = self.gene_list.loc[(self.gene_list[self.gene_list_lookup].isin(genotypes), :)] else: genes = self.design.index.isin(genotypes) gene_map = dict(zip(genes[self.gene_list_lookup].tolist(), genes[self.gene_list_index].tolist())) self.meta_data[self.metadata_expression_lookup] = self.meta_data[self.metadata_expression_lookup].map(gene_map) for (idx, row) in self.meta_data.iterrows(): if pd.isnull(row[self.metadata_expression_lookup]): continue try: new_value = self.tfa_adj_func(row[self.metadata_expression_lookup]) self.design.loc[(row[self.metadata_expression_lookup], idx)] = new_value except KeyError: continue
Set design values according to metadata :return:
inferelator_ng/single_cell_workflow.py
apply_metadata_to_activity
asistradition/inferelator_ng
1
python
def apply_metadata_to_activity(self): '\n Set design values according to metadata\n :return:\n ' utils.Debug.vprint('Modifying Transcription Factor Activity ... ') self.meta_data[self.metadata_expression_lookup] = self.meta_data[self.metadata_expression_lookup].str.upper() genotypes = self.meta_data[self.metadata_expression_lookup].unique().tolist() if (self.gene_list is not None): genes = self.gene_list.loc[(self.gene_list[self.gene_list_lookup].isin(genotypes), :)] else: genes = self.design.index.isin(genotypes) gene_map = dict(zip(genes[self.gene_list_lookup].tolist(), genes[self.gene_list_index].tolist())) self.meta_data[self.metadata_expression_lookup] = self.meta_data[self.metadata_expression_lookup].map(gene_map) for (idx, row) in self.meta_data.iterrows(): if pd.isnull(row[self.metadata_expression_lookup]): continue try: new_value = self.tfa_adj_func(row[self.metadata_expression_lookup]) self.design.loc[(row[self.metadata_expression_lookup], idx)] = new_value except KeyError: continue
def apply_metadata_to_activity(self): '\n Set design values according to metadata\n :return:\n ' utils.Debug.vprint('Modifying Transcription Factor Activity ... ') self.meta_data[self.metadata_expression_lookup] = self.meta_data[self.metadata_expression_lookup].str.upper() genotypes = self.meta_data[self.metadata_expression_lookup].unique().tolist() if (self.gene_list is not None): genes = self.gene_list.loc[(self.gene_list[self.gene_list_lookup].isin(genotypes), :)] else: genes = self.design.index.isin(genotypes) gene_map = dict(zip(genes[self.gene_list_lookup].tolist(), genes[self.gene_list_index].tolist())) self.meta_data[self.metadata_expression_lookup] = self.meta_data[self.metadata_expression_lookup].map(gene_map) for (idx, row) in self.meta_data.iterrows(): if pd.isnull(row[self.metadata_expression_lookup]): continue try: new_value = self.tfa_adj_func(row[self.metadata_expression_lookup]) self.design.loc[(row[self.metadata_expression_lookup], idx)] = new_value except KeyError: continue<|docstring|>Set design values according to metadata :return:<|endoftext|>
f14180810421e77be96d1ea2c935b01347d9a65a620b246031c64b1b686c1e3a
def get_truth_set(self): '\n Get gene fusions from the truth set\n args : file_truth <file.dat> \n return : FG_truth <list>\n ' with open(self.file_truth, 'r') as file: FG_truth = [line.strip().split('|')[1] for line in file] print('truth') print(FG_truth) return FG_truth
Get gene fusions from the truth set args : file_truth <file.dat> return : FG_truth <list>
M2-Internship-Scripts/extract_geneFusions.py
get_truth_set
Browco/sampleContributions
0
python
def get_truth_set(self): '\n Get gene fusions from the truth set\n args : file_truth <file.dat> \n return : FG_truth <list>\n ' with open(self.file_truth, 'r') as file: FG_truth = [line.strip().split('|')[1] for line in file] print('truth') print(FG_truth) return FG_truth
def get_truth_set(self): '\n Get gene fusions from the truth set\n args : file_truth <file.dat> \n return : FG_truth <list>\n ' with open(self.file_truth, 'r') as file: FG_truth = [line.strip().split('|')[1] for line in file] print('truth') print(FG_truth) return FG_truth<|docstring|>Get gene fusions from the truth set args : file_truth <file.dat> return : FG_truth <list><|endoftext|>
0353d69e66391f91a50191c1e0b28ffdd44533dce877355363d0e194c46da9de
def recognize_FGDetection_tool(self): '\n Recognize by which tool the FG file was created\n args : fusion_file <file.tsv> \n return : toolName <str>\n ' toolName = None with open(self.fusion_file) as ffile: first_line = ffile.readline() if (first_line.startswith('#FusionName') and (len(first_line.strip().split('\t')) > 14)): toolName = 'STARFUSION' elif first_line.startswith('#gene1'): toolName = 'ARRIBA' elif first_line.startswith('# chrom1'): toolName = 'SQUID' return toolName
Recognize by which tool the FG file was created args : fusion_file <file.tsv> return : toolName <str>
M2-Internship-Scripts/extract_geneFusions.py
recognize_FGDetection_tool
Browco/sampleContributions
0
python
def recognize_FGDetection_tool(self): '\n Recognize by which tool the FG file was created\n args : fusion_file <file.tsv> \n return : toolName <str>\n ' toolName = None with open(self.fusion_file) as ffile: first_line = ffile.readline() if (first_line.startswith('#FusionName') and (len(first_line.strip().split('\t')) > 14)): toolName = 'STARFUSION' elif first_line.startswith('#gene1'): toolName = 'ARRIBA' elif first_line.startswith('# chrom1'): toolName = 'SQUID' return toolName
def recognize_FGDetection_tool(self): '\n Recognize by which tool the FG file was created\n args : fusion_file <file.tsv> \n return : toolName <str>\n ' toolName = None with open(self.fusion_file) as ffile: first_line = ffile.readline() if (first_line.startswith('#FusionName') and (len(first_line.strip().split('\t')) > 14)): toolName = 'STARFUSION' elif first_line.startswith('#gene1'): toolName = 'ARRIBA' elif first_line.startswith('# chrom1'): toolName = 'SQUID' return toolName<|docstring|>Recognize by which tool the FG file was created args : fusion_file <file.tsv> return : toolName <str><|endoftext|>
43d8bbc83e89af7e6a7e80d409aaeaf89a93db917eb9956ed8c058313b649a25
def get_predicted_FG_from_merged(self): ' Retrieve the Gene fusions and tool used according to their specific\n columns in the different FG detection tools output. Gene Fusion will be named\n like the STAR-FUSION output : GENE1--GENE2 \n args : fusion_file <file.tsv> \n dict_tool_FG <dict> \n ' gene_fusion = [] dict_tool_FG = {} with open(self.fusion_file) as ffile: if (os.path.getsize(self.fusion_file) != 0): gene_fusion = [line.strip() for line in ffile if ((not line.startswith('.')) and (line not in gene_fusion))] print(gene_fusion) else: gene_fusion = [] dict_tool_FG['combinedPred'] = gene_fusion print('predicted') print(dict_tool_FG) return dict_tool_FG
Retrieve the Gene fusions and tool used according to their specific columns in the different FG detection tools output. Gene Fusion will be named like the STAR-FUSION output : GENE1--GENE2 args : fusion_file <file.tsv> dict_tool_FG <dict>
M2-Internship-Scripts/extract_geneFusions.py
get_predicted_FG_from_merged
Browco/sampleContributions
0
python
def get_predicted_FG_from_merged(self): ' Retrieve the Gene fusions and tool used according to their specific\n columns in the different FG detection tools output. Gene Fusion will be named\n like the STAR-FUSION output : GENE1--GENE2 \n args : fusion_file <file.tsv> \n dict_tool_FG <dict> \n ' gene_fusion = [] dict_tool_FG = {} with open(self.fusion_file) as ffile: if (os.path.getsize(self.fusion_file) != 0): gene_fusion = [line.strip() for line in ffile if ((not line.startswith('.')) and (line not in gene_fusion))] print(gene_fusion) else: gene_fusion = [] dict_tool_FG['combinedPred'] = gene_fusion print('predicted') print(dict_tool_FG) return dict_tool_FG
def get_predicted_FG_from_merged(self): ' Retrieve the Gene fusions and tool used according to their specific\n columns in the different FG detection tools output. Gene Fusion will be named\n like the STAR-FUSION output : GENE1--GENE2 \n args : fusion_file <file.tsv> \n dict_tool_FG <dict> \n ' gene_fusion = [] dict_tool_FG = {} with open(self.fusion_file) as ffile: if (os.path.getsize(self.fusion_file) != 0): gene_fusion = [line.strip() for line in ffile if ((not line.startswith('.')) and (line not in gene_fusion))] print(gene_fusion) else: gene_fusion = [] dict_tool_FG['combinedPred'] = gene_fusion print('predicted') print(dict_tool_FG) return dict_tool_FG<|docstring|>Retrieve the Gene fusions and tool used according to their specific columns in the different FG detection tools output. Gene Fusion will be named like the STAR-FUSION output : GENE1--GENE2 args : fusion_file <file.tsv> dict_tool_FG <dict><|endoftext|>
5cb91fff4d39a91444591e3bfbe73b5c1363e129c0a86832bf2eee5e4c01400d
def get_predicted_FG(self): ' Retrieve the Gene fusions and tool used according to their specific\n columns in the different FG detection tools output. Gene Fusion will be named\n like the STAR-FUSION output : GENE1--GENE2 \n args : fusion_file <file.tsv> \n dict_tool_FG <dict> \n ' gene_fusion = [] toolName = self.recognize_FGDetection_tool() dict_tool_FG = {} with open(self.fusion_file) as ffile: next(ffile) if (toolName == 'STARFUSION'): gene_fusion = [line.strip().split('\t')[0].upper() for line in ffile] elif (toolName == 'ARRIBA'): gene_fusion = [((line.strip().split('\t')[0].upper() + '--') + line.strip().split('\t')[1].upper()) for line in ffile] elif (toolName == 'SQUID'): gene_fusion = [line.strip().split('\t')[11].upper().replace(':', '--') for line in ffile] dict_tool_FG[toolName] = gene_fusion return dict_tool_FG
Retrieve the Gene fusions and tool used according to their specific columns in the different FG detection tools output. Gene Fusion will be named like the STAR-FUSION output : GENE1--GENE2 args : fusion_file <file.tsv> dict_tool_FG <dict>
M2-Internship-Scripts/extract_geneFusions.py
get_predicted_FG
Browco/sampleContributions
0
python
def get_predicted_FG(self): ' Retrieve the Gene fusions and tool used according to their specific\n columns in the different FG detection tools output. Gene Fusion will be named\n like the STAR-FUSION output : GENE1--GENE2 \n args : fusion_file <file.tsv> \n dict_tool_FG <dict> \n ' gene_fusion = [] toolName = self.recognize_FGDetection_tool() dict_tool_FG = {} with open(self.fusion_file) as ffile: next(ffile) if (toolName == 'STARFUSION'): gene_fusion = [line.strip().split('\t')[0].upper() for line in ffile] elif (toolName == 'ARRIBA'): gene_fusion = [((line.strip().split('\t')[0].upper() + '--') + line.strip().split('\t')[1].upper()) for line in ffile] elif (toolName == 'SQUID'): gene_fusion = [line.strip().split('\t')[11].upper().replace(':', '--') for line in ffile] dict_tool_FG[toolName] = gene_fusion return dict_tool_FG
def get_predicted_FG(self): ' Retrieve the Gene fusions and tool used according to their specific\n columns in the different FG detection tools output. Gene Fusion will be named\n like the STAR-FUSION output : GENE1--GENE2 \n args : fusion_file <file.tsv> \n dict_tool_FG <dict> \n ' gene_fusion = [] toolName = self.recognize_FGDetection_tool() dict_tool_FG = {} with open(self.fusion_file) as ffile: next(ffile) if (toolName == 'STARFUSION'): gene_fusion = [line.strip().split('\t')[0].upper() for line in ffile] elif (toolName == 'ARRIBA'): gene_fusion = [((line.strip().split('\t')[0].upper() + '--') + line.strip().split('\t')[1].upper()) for line in ffile] elif (toolName == 'SQUID'): gene_fusion = [line.strip().split('\t')[11].upper().replace(':', '--') for line in ffile] dict_tool_FG[toolName] = gene_fusion return dict_tool_FG<|docstring|>Retrieve the Gene fusions and tool used according to their specific columns in the different FG detection tools output. Gene Fusion will be named like the STAR-FUSION output : GENE1--GENE2 args : fusion_file <file.tsv> dict_tool_FG <dict><|endoftext|>
36e1f9a6d917674395a5da305d8684a3e5cb39c378f4de0f013a885c2f7d6d0f
def write_fusionGenes(self, output): ' Write a file with only fusion genes\n args : predicted_FG <dict>\n return : FG_file <list_FG.txt>\n ' prefix = self.fusion_file fg_dict = self.get_predicted_FG() print(fg_dict) for (tool, FGs) in fg_dict.items(): fusionGenes = {} basefile = (('list_FG_' + str(tool)) + '.txt') namefile = join(output, basefile) with open(namefile, 'a+') as FG_file: for FG in FGs: if ((FG not in fusionGenes.values()) and ((FG != '.') and (FG.split('--')[0] != FG.split('--')[1])) and (',' not in FG)): fusionGenes[tool] = FG FG_file.write((FG + '\n'))
Write a file with only fusion genes args : predicted_FG <dict> return : FG_file <list_FG.txt>
M2-Internship-Scripts/extract_geneFusions.py
write_fusionGenes
Browco/sampleContributions
0
python
def write_fusionGenes(self, output): ' Write a file with only fusion genes\n args : predicted_FG <dict>\n return : FG_file <list_FG.txt>\n ' prefix = self.fusion_file fg_dict = self.get_predicted_FG() print(fg_dict) for (tool, FGs) in fg_dict.items(): fusionGenes = {} basefile = (('list_FG_' + str(tool)) + '.txt') namefile = join(output, basefile) with open(namefile, 'a+') as FG_file: for FG in FGs: if ((FG not in fusionGenes.values()) and ((FG != '.') and (FG.split('--')[0] != FG.split('--')[1])) and (',' not in FG)): fusionGenes[tool] = FG FG_file.write((FG + '\n'))
def write_fusionGenes(self, output): ' Write a file with only fusion genes\n args : predicted_FG <dict>\n return : FG_file <list_FG.txt>\n ' prefix = self.fusion_file fg_dict = self.get_predicted_FG() print(fg_dict) for (tool, FGs) in fg_dict.items(): fusionGenes = {} basefile = (('list_FG_' + str(tool)) + '.txt') namefile = join(output, basefile) with open(namefile, 'a+') as FG_file: for FG in FGs: if ((FG not in fusionGenes.values()) and ((FG != '.') and (FG.split('--')[0] != FG.split('--')[1])) and (',' not in FG)): fusionGenes[tool] = FG FG_file.write((FG + '\n'))<|docstring|>Write a file with only fusion genes args : predicted_FG <dict> return : FG_file <list_FG.txt><|endoftext|>
1bd74f336e2174e4b1af2450dbf2e1e6fa00c79366a091ade9b82cf71a5f3c08
def stats_per_gene_on_chunks_for_genome(env, df_summary_genome, **kwargs): "Input is summary dataframe for all entries of a given genome (including all chunks)\n Each row has the following:\n Genome: Label of genome\n Seqname: Sequence name/accession number\n Left-Chunk: left location of chunk in original sequence (inclusive)\n Right-Chunk right location of chunk in original sequence (inclusive)\n Key: made from (possibly partial) 3' end, seqname name, strand\n For each tool:\n Left, right, partial-3', partial-5'\n\n " list_entries = list() for (genome, df_genome) in df_summary_genome.groupby('Genome', as_index=False): pf_sequence = os_join(env['pd-data'], genome, 'sequence.fasta') sequences = SeqIO.to_dict(SeqIO.parse(pf_sequence, 'fasta')) clade = None if ('Clade' in df_genome.columns): clade = df_genome.at[(df_genome.index[0], 'Clade')] genome_gc = compute_gc(sequences) reference_tools = get_value(kwargs, 'reference_tools', None) if reference_tools: reference_tools = sorted(reference_tools) list_reference_labels = list() if (reference_tools is not None): list_reference_labels = [read_labels_from_file(os_join(env['pd-runs'], genome, rt, 'prediction.gff'), ignore_partial=False, shift=(- 1)) for rt in reference_tools] merged_reference_labels = None if (len(list_reference_labels) > 1): merged_reference_labels = LabelsComparisonDetailed(list_reference_labels[0], list_reference_labels[1]).match_3p_5p('a') for i in range(2, len(list_reference_labels)): merged_reference_labels = LabelsComparisonDetailed(merged_reference_labels, list_reference_labels[i]).match_3p_5p('a') for (chunk_size, df_chunk) in df_genome.groupby('Chunk Size', as_index=False): tool_to_labels = {df_chunk.at[(idx, 'Tool')]: read_labels_from_file(df_chunk.at[(idx, 'Predictions')], shift=(- 1), ignore_partial=False) for idx in df_chunk.index} seqname_to_chunks = dict() for labels in tool_to_labels.values(): for lab in labels: seqname = lab.seqname() if (seqname not in seqname_to_chunks): seqname_to_chunks[seqname] = set() seqname_to_chunks[seqname].add((int(lab.get_attribute_value('chunk_left_in_original')), int(lab.get_attribute_value('chunk_right_in_original')))) chunked_reference_labels = dict() if (len(list_reference_labels) > 0): chunked_reference_labels = {ref: apply_genome_splitter_to_labels(seqname_to_chunks, labels) for (ref, labels) in zip(reference_tools, list_reference_labels)} if (merged_reference_labels is not None): chunked_reference_labels['='.join(reference_tools)] = apply_genome_splitter_to_labels(seqname_to_chunks, merged_reference_labels) name_to_labels = copy.copy(tool_to_labels) name_to_labels.update(chunked_reference_labels) all_labels = (list(chunked_reference_labels.values()) + list(tool_to_labels.values())) keys_3prime = get_unique_gene_keys(*all_labels) for key in keys_3prime: entry = dict() shortest_label = None for t in name_to_labels.keys(): label = name_to_labels[t].get_by_3prime_key(key) if (label is None): entry[f'5p-{t}'] = None entry[f'3p-{t}'] = None else: entry[f'5p-{t}'] = label.get_5prime() entry[f'3p-{t}'] = label.get_3prime() if (shortest_label is None): shortest_label = label elif (shortest_label.length() < label.length()): shortest_label = label entry[f'Partial3p-{t}'] = label.incomplete_at_3prime() entry[f'Partial5p-{t}'] = label.incomplete_at_5prime() gene_gc = 0 list_entries.append({'3p-key': key, 'Genome': genome, 'Genome GC': genome_gc, 'Gene GC': gene_gc, 'Chunk Size': chunk_size, 'Runtime': df_chunk['Runtime'].mean(), 'Clade': clade, **entry}) return pd.DataFrame(list_entries)
Input is summary dataframe for all entries of a given genome (including all chunks) Each row has the following: Genome: Label of genome Seqname: Sequence name/accession number Left-Chunk: left location of chunk in original sequence (inclusive) Right-Chunk right location of chunk in original sequence (inclusive) Key: made from (possibly partial) 3' end, seqname name, strand For each tool: Left, right, partial-3', partial-5'
code/python/driver/stats_per_gene_on_chunk.py
stats_per_gene_on_chunks_for_genome
alguru/metagenemark-2
0
python
def stats_per_gene_on_chunks_for_genome(env, df_summary_genome, **kwargs): "Input is summary dataframe for all entries of a given genome (including all chunks)\n Each row has the following:\n Genome: Label of genome\n Seqname: Sequence name/accession number\n Left-Chunk: left location of chunk in original sequence (inclusive)\n Right-Chunk right location of chunk in original sequence (inclusive)\n Key: made from (possibly partial) 3' end, seqname name, strand\n For each tool:\n Left, right, partial-3', partial-5'\n\n " list_entries = list() for (genome, df_genome) in df_summary_genome.groupby('Genome', as_index=False): pf_sequence = os_join(env['pd-data'], genome, 'sequence.fasta') sequences = SeqIO.to_dict(SeqIO.parse(pf_sequence, 'fasta')) clade = None if ('Clade' in df_genome.columns): clade = df_genome.at[(df_genome.index[0], 'Clade')] genome_gc = compute_gc(sequences) reference_tools = get_value(kwargs, 'reference_tools', None) if reference_tools: reference_tools = sorted(reference_tools) list_reference_labels = list() if (reference_tools is not None): list_reference_labels = [read_labels_from_file(os_join(env['pd-runs'], genome, rt, 'prediction.gff'), ignore_partial=False, shift=(- 1)) for rt in reference_tools] merged_reference_labels = None if (len(list_reference_labels) > 1): merged_reference_labels = LabelsComparisonDetailed(list_reference_labels[0], list_reference_labels[1]).match_3p_5p('a') for i in range(2, len(list_reference_labels)): merged_reference_labels = LabelsComparisonDetailed(merged_reference_labels, list_reference_labels[i]).match_3p_5p('a') for (chunk_size, df_chunk) in df_genome.groupby('Chunk Size', as_index=False): tool_to_labels = {df_chunk.at[(idx, 'Tool')]: read_labels_from_file(df_chunk.at[(idx, 'Predictions')], shift=(- 1), ignore_partial=False) for idx in df_chunk.index} seqname_to_chunks = dict() for labels in tool_to_labels.values(): for lab in labels: seqname = lab.seqname() if (seqname not in seqname_to_chunks): seqname_to_chunks[seqname] = set() seqname_to_chunks[seqname].add((int(lab.get_attribute_value('chunk_left_in_original')), int(lab.get_attribute_value('chunk_right_in_original')))) chunked_reference_labels = dict() if (len(list_reference_labels) > 0): chunked_reference_labels = {ref: apply_genome_splitter_to_labels(seqname_to_chunks, labels) for (ref, labels) in zip(reference_tools, list_reference_labels)} if (merged_reference_labels is not None): chunked_reference_labels['='.join(reference_tools)] = apply_genome_splitter_to_labels(seqname_to_chunks, merged_reference_labels) name_to_labels = copy.copy(tool_to_labels) name_to_labels.update(chunked_reference_labels) all_labels = (list(chunked_reference_labels.values()) + list(tool_to_labels.values())) keys_3prime = get_unique_gene_keys(*all_labels) for key in keys_3prime: entry = dict() shortest_label = None for t in name_to_labels.keys(): label = name_to_labels[t].get_by_3prime_key(key) if (label is None): entry[f'5p-{t}'] = None entry[f'3p-{t}'] = None else: entry[f'5p-{t}'] = label.get_5prime() entry[f'3p-{t}'] = label.get_3prime() if (shortest_label is None): shortest_label = label elif (shortest_label.length() < label.length()): shortest_label = label entry[f'Partial3p-{t}'] = label.incomplete_at_3prime() entry[f'Partial5p-{t}'] = label.incomplete_at_5prime() gene_gc = 0 list_entries.append({'3p-key': key, 'Genome': genome, 'Genome GC': genome_gc, 'Gene GC': gene_gc, 'Chunk Size': chunk_size, 'Runtime': df_chunk['Runtime'].mean(), 'Clade': clade, **entry}) return pd.DataFrame(list_entries)
def stats_per_gene_on_chunks_for_genome(env, df_summary_genome, **kwargs): "Input is summary dataframe for all entries of a given genome (including all chunks)\n Each row has the following:\n Genome: Label of genome\n Seqname: Sequence name/accession number\n Left-Chunk: left location of chunk in original sequence (inclusive)\n Right-Chunk right location of chunk in original sequence (inclusive)\n Key: made from (possibly partial) 3' end, seqname name, strand\n For each tool:\n Left, right, partial-3', partial-5'\n\n " list_entries = list() for (genome, df_genome) in df_summary_genome.groupby('Genome', as_index=False): pf_sequence = os_join(env['pd-data'], genome, 'sequence.fasta') sequences = SeqIO.to_dict(SeqIO.parse(pf_sequence, 'fasta')) clade = None if ('Clade' in df_genome.columns): clade = df_genome.at[(df_genome.index[0], 'Clade')] genome_gc = compute_gc(sequences) reference_tools = get_value(kwargs, 'reference_tools', None) if reference_tools: reference_tools = sorted(reference_tools) list_reference_labels = list() if (reference_tools is not None): list_reference_labels = [read_labels_from_file(os_join(env['pd-runs'], genome, rt, 'prediction.gff'), ignore_partial=False, shift=(- 1)) for rt in reference_tools] merged_reference_labels = None if (len(list_reference_labels) > 1): merged_reference_labels = LabelsComparisonDetailed(list_reference_labels[0], list_reference_labels[1]).match_3p_5p('a') for i in range(2, len(list_reference_labels)): merged_reference_labels = LabelsComparisonDetailed(merged_reference_labels, list_reference_labels[i]).match_3p_5p('a') for (chunk_size, df_chunk) in df_genome.groupby('Chunk Size', as_index=False): tool_to_labels = {df_chunk.at[(idx, 'Tool')]: read_labels_from_file(df_chunk.at[(idx, 'Predictions')], shift=(- 1), ignore_partial=False) for idx in df_chunk.index} seqname_to_chunks = dict() for labels in tool_to_labels.values(): for lab in labels: seqname = lab.seqname() if (seqname not in seqname_to_chunks): seqname_to_chunks[seqname] = set() seqname_to_chunks[seqname].add((int(lab.get_attribute_value('chunk_left_in_original')), int(lab.get_attribute_value('chunk_right_in_original')))) chunked_reference_labels = dict() if (len(list_reference_labels) > 0): chunked_reference_labels = {ref: apply_genome_splitter_to_labels(seqname_to_chunks, labels) for (ref, labels) in zip(reference_tools, list_reference_labels)} if (merged_reference_labels is not None): chunked_reference_labels['='.join(reference_tools)] = apply_genome_splitter_to_labels(seqname_to_chunks, merged_reference_labels) name_to_labels = copy.copy(tool_to_labels) name_to_labels.update(chunked_reference_labels) all_labels = (list(chunked_reference_labels.values()) + list(tool_to_labels.values())) keys_3prime = get_unique_gene_keys(*all_labels) for key in keys_3prime: entry = dict() shortest_label = None for t in name_to_labels.keys(): label = name_to_labels[t].get_by_3prime_key(key) if (label is None): entry[f'5p-{t}'] = None entry[f'3p-{t}'] = None else: entry[f'5p-{t}'] = label.get_5prime() entry[f'3p-{t}'] = label.get_3prime() if (shortest_label is None): shortest_label = label elif (shortest_label.length() < label.length()): shortest_label = label entry[f'Partial3p-{t}'] = label.incomplete_at_3prime() entry[f'Partial5p-{t}'] = label.incomplete_at_5prime() gene_gc = 0 list_entries.append({'3p-key': key, 'Genome': genome, 'Genome GC': genome_gc, 'Gene GC': gene_gc, 'Chunk Size': chunk_size, 'Runtime': df_chunk['Runtime'].mean(), 'Clade': clade, **entry}) return pd.DataFrame(list_entries)<|docstring|>Input is summary dataframe for all entries of a given genome (including all chunks) Each row has the following: Genome: Label of genome Seqname: Sequence name/accession number Left-Chunk: left location of chunk in original sequence (inclusive) Right-Chunk right location of chunk in original sequence (inclusive) Key: made from (possibly partial) 3' end, seqname name, strand For each tool: Left, right, partial-3', partial-5'<|endoftext|>
5cc603eab7ab773f30e9b90ef19a7a8acbfa14ee12c34ae69eae62414593ead8
def escapement(): 'Run a query' q = Query(orgs=['nteract'], repos=['nteract'], user='willingc') q.display_settings() query_string = q.compose_query() result = run_query(query_string) generate_report(result) create_dataframe(result)
Run a query
escapement/escapement.py
escapement
willingc/escapement
0
python
def escapement(): q = Query(orgs=['nteract'], repos=['nteract'], user='willingc') q.display_settings() query_string = q.compose_query() result = run_query(query_string) generate_report(result) create_dataframe(result)
def escapement(): q = Query(orgs=['nteract'], repos=['nteract'], user='willingc') q.display_settings() query_string = q.compose_query() result = run_query(query_string) generate_report(result) create_dataframe(result)<|docstring|>Run a query<|endoftext|>
9850ecf5433e52888765b2eb1b3af823c1353feb165cfe0647f1624f970399d3
def __init__(self, multi_func_caller, worker_manager, model=None, options=None, reporter=None): ' Constructor. ' assert (isinstance(multi_func_caller, MultiFunctionCaller) and (not isinstance(multi_func_caller, FunctionCaller))) self.multi_func_caller = multi_func_caller self.domain = self.multi_func_caller.domain super(MultiObjectiveOptimiser, self).__init__(multi_func_caller, worker_manager, model, options, reporter)
Constructor.
dragonfly/opt/multiobjective_optimiser.py
__init__
crcollins/dragonfly
0
python
def __init__(self, multi_func_caller, worker_manager, model=None, options=None, reporter=None): ' ' assert (isinstance(multi_func_caller, MultiFunctionCaller) and (not isinstance(multi_func_caller, FunctionCaller))) self.multi_func_caller = multi_func_caller self.domain = self.multi_func_caller.domain super(MultiObjectiveOptimiser, self).__init__(multi_func_caller, worker_manager, model, options, reporter)
def __init__(self, multi_func_caller, worker_manager, model=None, options=None, reporter=None): ' ' assert (isinstance(multi_func_caller, MultiFunctionCaller) and (not isinstance(multi_func_caller, FunctionCaller))) self.multi_func_caller = multi_func_caller self.domain = self.multi_func_caller.domain super(MultiObjectiveOptimiser, self).__init__(multi_func_caller, worker_manager, model, options, reporter)<|docstring|>Constructor.<|endoftext|>
234ffe24bfb85da447a96931b7fc01467aba1f7780ac3ff992411babc74e5734
def _exd_child_set_up(self): ' Set up for the optimisation. ' if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) self._moo_set_up() self._multi_opt_method_set_up() self.prev_eval_vals = []
Set up for the optimisation.
dragonfly/opt/multiobjective_optimiser.py
_exd_child_set_up
crcollins/dragonfly
0
python
def _exd_child_set_up(self): ' ' if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) self._moo_set_up() self._multi_opt_method_set_up() self.prev_eval_vals = []
def _exd_child_set_up(self): ' ' if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) self._moo_set_up() self._multi_opt_method_set_up() self.prev_eval_vals = []<|docstring|>Set up for the optimisation.<|endoftext|>
838f787a27b693030c371a270b326aa90819dc90ae6aa0ff642131ae4a5522e5
def _moo_set_up(self): ' Set up for black-box optimisation. ' self.curr_pareto_vals = [] self.curr_pareto_points = [] self.curr_true_pareto_vals = [] self.curr_true_pareto_points = [] self.history.query_vals = [] self.history.query_true_vals = [] self.history.curr_pareto_vals = [] self.history.curr_pareto_points = [] self.history.curr_true_pareto_vals = [] self.history.curr_true_pareto_points = [] if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) self.to_copy_from_qinfo_to_history['val'] = 'query_vals' self.to_copy_from_qinfo_to_history['true_val'] = 'query_true_vals' self.history.prev_eval_points = [] self.history.prev_eval_vals = [] self.prev_eval_vals = [] self.prev_eval_true_vals = []
Set up for black-box optimisation.
dragonfly/opt/multiobjective_optimiser.py
_moo_set_up
crcollins/dragonfly
0
python
def _moo_set_up(self): ' ' self.curr_pareto_vals = [] self.curr_pareto_points = [] self.curr_true_pareto_vals = [] self.curr_true_pareto_points = [] self.history.query_vals = [] self.history.query_true_vals = [] self.history.curr_pareto_vals = [] self.history.curr_pareto_points = [] self.history.curr_true_pareto_vals = [] self.history.curr_true_pareto_points = [] if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) self.to_copy_from_qinfo_to_history['val'] = 'query_vals' self.to_copy_from_qinfo_to_history['true_val'] = 'query_true_vals' self.history.prev_eval_points = [] self.history.prev_eval_vals = [] self.prev_eval_vals = [] self.prev_eval_true_vals = []
def _moo_set_up(self): ' ' self.curr_pareto_vals = [] self.curr_pareto_points = [] self.curr_true_pareto_vals = [] self.curr_true_pareto_points = [] self.history.query_vals = [] self.history.query_true_vals = [] self.history.curr_pareto_vals = [] self.history.curr_pareto_points = [] self.history.curr_true_pareto_vals = [] self.history.curr_true_pareto_points = [] if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) self.to_copy_from_qinfo_to_history['val'] = 'query_vals' self.to_copy_from_qinfo_to_history['true_val'] = 'query_true_vals' self.history.prev_eval_points = [] self.history.prev_eval_vals = [] self.prev_eval_vals = [] self.prev_eval_true_vals = []<|docstring|>Set up for black-box optimisation.<|endoftext|>
e0004df450768d5fa4087debb326e439d344cac407cbc27ed9a00186b8e25614
def _multi_opt_method_set_up(self): ' Any set up for the specific optimisation method. ' raise NotImplementedError('Implement in Optimisation Method class.')
Any set up for the specific optimisation method.
dragonfly/opt/multiobjective_optimiser.py
_multi_opt_method_set_up
crcollins/dragonfly
0
python
def _multi_opt_method_set_up(self): ' ' raise NotImplementedError('Implement in Optimisation Method class.')
def _multi_opt_method_set_up(self): ' ' raise NotImplementedError('Implement in Optimisation Method class.')<|docstring|>Any set up for the specific optimisation method.<|endoftext|>
2e555a43aa24963e66d283f1656768c5081f7345ddc27c2b021d0f2b6a06ef13
def _get_problem_str(self): ' Description of the problem. ' return 'Multi-objective Optimisation'
Description of the problem.
dragonfly/opt/multiobjective_optimiser.py
_get_problem_str
crcollins/dragonfly
0
python
def _get_problem_str(self): ' ' return 'Multi-objective Optimisation'
def _get_problem_str(self): ' ' return 'Multi-objective Optimisation'<|docstring|>Description of the problem.<|endoftext|>
6b3f95ac4fd28fe19b39c935ffc13445afadf46b8eb1b80f4f3bc5b6e6682b9d
def _exd_child_update_history(self, qinfo): ' Updates to the history specific to optimisation. ' if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) else: self._update_opt_point_and_val(qinfo) self.history.curr_pareto_vals.append(self.curr_pareto_vals) self.history.curr_pareto_points.append(self.curr_pareto_points) self.history.curr_true_pareto_vals.append(self.curr_true_pareto_vals) self.history.curr_true_pareto_points.append(self.curr_true_pareto_points) self._multi_opt_method_update_history(qinfo)
Updates to the history specific to optimisation.
dragonfly/opt/multiobjective_optimiser.py
_exd_child_update_history
crcollins/dragonfly
0
python
def _exd_child_update_history(self, qinfo): ' ' if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) else: self._update_opt_point_and_val(qinfo) self.history.curr_pareto_vals.append(self.curr_pareto_vals) self.history.curr_pareto_points.append(self.curr_pareto_points) self.history.curr_true_pareto_vals.append(self.curr_true_pareto_vals) self.history.curr_true_pareto_points.append(self.curr_true_pareto_points) self._multi_opt_method_update_history(qinfo)
def _exd_child_update_history(self, qinfo): ' ' if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) else: self._update_opt_point_and_val(qinfo) self.history.curr_pareto_vals.append(self.curr_pareto_vals) self.history.curr_pareto_points.append(self.curr_pareto_points) self.history.curr_true_pareto_vals.append(self.curr_true_pareto_vals) self.history.curr_true_pareto_points.append(self.curr_true_pareto_points) self._multi_opt_method_update_history(qinfo)<|docstring|>Updates to the history specific to optimisation.<|endoftext|>
28a614cc206f3389078b2b59fe57c7bf8c0521218dc66adacadf2640d6aaadf2
def _update_opt_point_and_val(self, qinfo, query_is_at_fidel_to_opt=None): ' Updates the optimum point and value according the data in qinfo.\n Can be overridden by a child class if you want to do anything differently.\n ' if (query_is_at_fidel_to_opt is not None): if (not query_is_at_fidel_to_opt): return (self.curr_pareto_vals, self.curr_pareto_points) = update_pareto_set(self.curr_pareto_vals, self.curr_pareto_points, qinfo.val, qinfo.point) (self.curr_true_pareto_vals, self.curr_true_pareto_points) = update_pareto_set(self.curr_true_pareto_vals, self.curr_true_pareto_points, qinfo.true_val, qinfo.point)
Updates the optimum point and value according the data in qinfo. Can be overridden by a child class if you want to do anything differently.
dragonfly/opt/multiobjective_optimiser.py
_update_opt_point_and_val
crcollins/dragonfly
0
python
def _update_opt_point_and_val(self, qinfo, query_is_at_fidel_to_opt=None): ' Updates the optimum point and value according the data in qinfo.\n Can be overridden by a child class if you want to do anything differently.\n ' if (query_is_at_fidel_to_opt is not None): if (not query_is_at_fidel_to_opt): return (self.curr_pareto_vals, self.curr_pareto_points) = update_pareto_set(self.curr_pareto_vals, self.curr_pareto_points, qinfo.val, qinfo.point) (self.curr_true_pareto_vals, self.curr_true_pareto_points) = update_pareto_set(self.curr_true_pareto_vals, self.curr_true_pareto_points, qinfo.true_val, qinfo.point)
def _update_opt_point_and_val(self, qinfo, query_is_at_fidel_to_opt=None): ' Updates the optimum point and value according the data in qinfo.\n Can be overridden by a child class if you want to do anything differently.\n ' if (query_is_at_fidel_to_opt is not None): if (not query_is_at_fidel_to_opt): return (self.curr_pareto_vals, self.curr_pareto_points) = update_pareto_set(self.curr_pareto_vals, self.curr_pareto_points, qinfo.val, qinfo.point) (self.curr_true_pareto_vals, self.curr_true_pareto_points) = update_pareto_set(self.curr_true_pareto_vals, self.curr_true_pareto_points, qinfo.true_val, qinfo.point)<|docstring|>Updates the optimum point and value according the data in qinfo. Can be overridden by a child class if you want to do anything differently.<|endoftext|>
c08a0e3cc65d491180870f8c25492ce7c3b1fd15eba6411d0fe4ddad231b2237
def _multi_opt_method_update_history(self, qinfo): ' Any updates to the history specific to the method. ' pass
Any updates to the history specific to the method.
dragonfly/opt/multiobjective_optimiser.py
_multi_opt_method_update_history
crcollins/dragonfly
0
python
def _multi_opt_method_update_history(self, qinfo): ' ' pass
def _multi_opt_method_update_history(self, qinfo): ' ' pass<|docstring|>Any updates to the history specific to the method.<|endoftext|>
31d27e6088b1a42e48cd0a3a3121a8f62a2a724d54295effcb6f2a14862c2d2e
def _get_exd_child_header_str(self): ' Header for black box optimisation. ' ret = '#Pareto=<num_pareto_optimal_points_found>' ret += self._get_opt_method_header_str() return ret
Header for black box optimisation.
dragonfly/opt/multiobjective_optimiser.py
_get_exd_child_header_str
crcollins/dragonfly
0
python
def _get_exd_child_header_str(self): ' ' ret = '#Pareto=<num_pareto_optimal_points_found>' ret += self._get_opt_method_header_str() return ret
def _get_exd_child_header_str(self): ' ' ret = '#Pareto=<num_pareto_optimal_points_found>' ret += self._get_opt_method_header_str() return ret<|docstring|>Header for black box optimisation.<|endoftext|>
ca929873f54cd0200848065caa5881fcef60cc5ed3bb9216b9609e65b4cda596
@classmethod def _get_opt_method_header_str(cls): ' Header for optimisation method. ' return ''
Header for optimisation method.
dragonfly/opt/multiobjective_optimiser.py
_get_opt_method_header_str
crcollins/dragonfly
0
python
@classmethod def _get_opt_method_header_str(cls): ' ' return
@classmethod def _get_opt_method_header_str(cls): ' ' return <|docstring|>Header for optimisation method.<|endoftext|>
b663ecb142369b67489c2b93f1aca2fbde49027729d5b04173a0c4865d1e66f0
def _get_exd_child_report_results_str(self): ' Returns a string describing the progress in optimisation. ' best_val_str = ('#Pareto: %d' % len(self.curr_pareto_vals)) opt_method_str = self._get_opt_method_report_results_str() return ((best_val_str + opt_method_str) + ', ')
Returns a string describing the progress in optimisation.
dragonfly/opt/multiobjective_optimiser.py
_get_exd_child_report_results_str
crcollins/dragonfly
0
python
def _get_exd_child_report_results_str(self): ' ' best_val_str = ('#Pareto: %d' % len(self.curr_pareto_vals)) opt_method_str = self._get_opt_method_report_results_str() return ((best_val_str + opt_method_str) + ', ')
def _get_exd_child_report_results_str(self): ' ' best_val_str = ('#Pareto: %d' % len(self.curr_pareto_vals)) opt_method_str = self._get_opt_method_report_results_str() return ((best_val_str + opt_method_str) + ', ')<|docstring|>Returns a string describing the progress in optimisation.<|endoftext|>
2f07a52cf1ee90c8d8a908f25cb467bac6f5444d9d1d54c01ac7ee666f3dc5d8
def _get_opt_method_report_results_str(self): ' Any details to include in a child method when reporting results.\n Can be overridden by a child class.\n ' return ''
Any details to include in a child method when reporting results. Can be overridden by a child class.
dragonfly/opt/multiobjective_optimiser.py
_get_opt_method_report_results_str
crcollins/dragonfly
0
python
def _get_opt_method_report_results_str(self): ' Any details to include in a child method when reporting results.\n Can be overridden by a child class.\n ' return
def _get_opt_method_report_results_str(self): ' Any details to include in a child method when reporting results.\n Can be overridden by a child class.\n ' return <|docstring|>Any details to include in a child method when reporting results. Can be overridden by a child class.<|endoftext|>
725a1c2a73927a2d5c3eed6f29f2e3c321a284b5038c65241254162b5c79aac1
def _exd_child_handle_prev_evals(self): ' Handles pre-evaluations. ' for qinfo in self.options.prev_evaluations.qinfos: if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) else: self._update_opt_point_and_val(qinfo) self.prev_eval_points.append(qinfo.point) self.prev_eval_vals.append(qinfo.val) self.history.prev_eval_points = self.prev_eval_points self.history.prev_eval_vals = self.prev_eval_vals
Handles pre-evaluations.
dragonfly/opt/multiobjective_optimiser.py
_exd_child_handle_prev_evals
crcollins/dragonfly
0
python
def _exd_child_handle_prev_evals(self): ' ' for qinfo in self.options.prev_evaluations.qinfos: if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) else: self._update_opt_point_and_val(qinfo) self.prev_eval_points.append(qinfo.point) self.prev_eval_vals.append(qinfo.val) self.history.prev_eval_points = self.prev_eval_points self.history.prev_eval_vals = self.prev_eval_vals
def _exd_child_handle_prev_evals(self): ' ' for qinfo in self.options.prev_evaluations.qinfos: if self.multi_func_caller.is_mf(): raise NotImplementedError(_NO_MF_FOR_MOO_ERR_MSG) else: self._update_opt_point_and_val(qinfo) self.prev_eval_points.append(qinfo.point) self.prev_eval_vals.append(qinfo.val) self.history.prev_eval_points = self.prev_eval_points self.history.prev_eval_vals = self.prev_eval_vals<|docstring|>Handles pre-evaluations.<|endoftext|>
2d9c94ad7e235add516d03956d28aed366eb629a7343ada21de9fa9527742f88
def _child_run_experiments_initialise(self): ' Handles any initialisation before running experiments. ' self._opt_method_optimise_initalise()
Handles any initialisation before running experiments.
dragonfly/opt/multiobjective_optimiser.py
_child_run_experiments_initialise
crcollins/dragonfly
0
python
def _child_run_experiments_initialise(self): ' ' self._opt_method_optimise_initalise()
def _child_run_experiments_initialise(self): ' ' self._opt_method_optimise_initalise()<|docstring|>Handles any initialisation before running experiments.<|endoftext|>
184d901bfdeb0d9b6ea956f30102faa302a53ad533317cb87807dba94149b359
def _opt_method_optimise_initalise(self): ' Any routine to run for a method just before optimisation routine. ' pass
Any routine to run for a method just before optimisation routine.
dragonfly/opt/multiobjective_optimiser.py
_opt_method_optimise_initalise
crcollins/dragonfly
0
python
def _opt_method_optimise_initalise(self): ' ' pass
def _opt_method_optimise_initalise(self): ' ' pass<|docstring|>Any routine to run for a method just before optimisation routine.<|endoftext|>
827c0fe0f7e85049d43656f93feda497b8be3bd31956f2337196e999418eff83
def optimise(self, max_capital): ' Calling optimise with optimise the function. A wrapper for run_experiments from\n BlackboxExperimenter. ' ret = self.run_experiments(max_capital) return ret
Calling optimise with optimise the function. A wrapper for run_experiments from BlackboxExperimenter.
dragonfly/opt/multiobjective_optimiser.py
optimise
crcollins/dragonfly
0
python
def optimise(self, max_capital): ' Calling optimise with optimise the function. A wrapper for run_experiments from\n BlackboxExperimenter. ' ret = self.run_experiments(max_capital) return ret
def optimise(self, max_capital): ' Calling optimise with optimise the function. A wrapper for run_experiments from\n BlackboxExperimenter. ' ret = self.run_experiments(max_capital) return ret<|docstring|>Calling optimise with optimise the function. A wrapper for run_experiments from BlackboxExperimenter.<|endoftext|>
6931fbc6f7469afb3e83ca57644b78c1da25dbe1827fff196b725b076f834fca
def _get_final_return_quantities(self): ' Return the curr_opt_val, curr_opt_point and history. ' return (self.curr_pareto_vals, self.curr_pareto_points, self.history)
Return the curr_opt_val, curr_opt_point and history.
dragonfly/opt/multiobjective_optimiser.py
_get_final_return_quantities
crcollins/dragonfly
0
python
def _get_final_return_quantities(self): ' ' return (self.curr_pareto_vals, self.curr_pareto_points, self.history)
def _get_final_return_quantities(self): ' ' return (self.curr_pareto_vals, self.curr_pareto_points, self.history)<|docstring|>Return the curr_opt_val, curr_opt_point and history.<|endoftext|>
31e4f1ca9169a3c3f178d77f7211c8835892634cc46d16a2ef29a365e0fc861f
def get_time_and_detonation_velocity(self): 'Read detonation velocity vs time from simulation results.\n\n Returns\n -------\n t: ndarray\n Array with time data\n d: ndarray\n Array with detonation velocity data\n\n ' return self._reader.get_time_and_detonation_velocity()
Read detonation velocity vs time from simulation results. Returns ------- t: ndarray Array with time data d: ndarray Array with detonation velocity data
code/saf/fm/linear/reader.py
get_time_and_detonation_velocity
ExplosiveJam/fickettmodel-reproducibility
1
python
def get_time_and_detonation_velocity(self): 'Read detonation velocity vs time from simulation results.\n\n Returns\n -------\n t: ndarray\n Array with time data\n d: ndarray\n Array with detonation velocity data\n\n ' return self._reader.get_time_and_detonation_velocity()
def get_time_and_detonation_velocity(self): 'Read detonation velocity vs time from simulation results.\n\n Returns\n -------\n t: ndarray\n Array with time data\n d: ndarray\n Array with detonation velocity data\n\n ' return self._reader.get_time_and_detonation_velocity()<|docstring|>Read detonation velocity vs time from simulation results. Returns ------- t: ndarray Array with time data d: ndarray Array with detonation velocity data<|endoftext|>
b42af50523c4dc9374cf9e7353f8fcc274ac79956ae07904a0fc1b5ff4f8945e
def get_time_and_normalized_detonation_velocity(self): 'Read detonation velocity vs time from simulation results.\n\n Returns\n -------\n t: ndarray\n Array with time data.\n d_normalized: ndarray\n Array with normalized detonation velocity data.\n\n ' return self._reader.get_time_and_normalized_detonation_velocity()
Read detonation velocity vs time from simulation results. Returns ------- t: ndarray Array with time data. d_normalized: ndarray Array with normalized detonation velocity data.
code/saf/fm/linear/reader.py
get_time_and_normalized_detonation_velocity
ExplosiveJam/fickettmodel-reproducibility
1
python
def get_time_and_normalized_detonation_velocity(self): 'Read detonation velocity vs time from simulation results.\n\n Returns\n -------\n t: ndarray\n Array with time data.\n d_normalized: ndarray\n Array with normalized detonation velocity data.\n\n ' return self._reader.get_time_and_normalized_detonation_velocity()
def get_time_and_normalized_detonation_velocity(self): 'Read detonation velocity vs time from simulation results.\n\n Returns\n -------\n t: ndarray\n Array with time data.\n d_normalized: ndarray\n Array with normalized detonation velocity data.\n\n ' return self._reader.get_time_and_normalized_detonation_velocity()<|docstring|>Read detonation velocity vs time from simulation results. Returns ------- t: ndarray Array with time data. d_normalized: ndarray Array with normalized detonation velocity data.<|endoftext|>
0e1ec44c08511ecebedd3c0e327f5060cfc2b4b1bd5757020bd558ee9bce3e97
def get_stability_info(self): "Read file with stability info for time series of detonation speed.\n\n Returns\n -------\n eigvals : list\n List with eigenvalues. Each element is a dictionary\n with keys {'growth_rate', 'frequency'}.\n\n Raises\n ------\n Exception\n If the file with stability information cannot be read.\n\n " eigvals = [] fit_file = os.path.join(self._results_dir, 'stability.txt') if (not os.path.isfile(fit_file)): raise ReaderError("Cannot find file 'stability.txt'.") with open(fit_file, 'r') as f: for line in f: if line.startswith('#'): continue if line.startswith('---'): break chunks = line.split() gr = float(chunks[0]) fr = float(chunks[1]) if len(eigvals): prev_eig = eigvals[(- 1)] if (type(prev_eig) is dict): if (fr == eigvals[(- 1)]['frequency']): eig_1 = eigvals.pop() eig_2 = {'growth_rate': gr, 'frequency': fr} eigs = [eig_1, eig_2] eigvals.append(eigs) else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) elif (type(prev_eig) is list): if (fr == prev_eig[(- 1)]['frequency']): eigs = eigvals.pop() eig_2 = {'growth_rate': gr, 'frequency': fr} eigs.append(eig_2) eigvals.append(eigs) else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) else: raise Exception('Cannot parse stability.txt') else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) return eigvals
Read file with stability info for time series of detonation speed. Returns ------- eigvals : list List with eigenvalues. Each element is a dictionary with keys {'growth_rate', 'frequency'}. Raises ------ Exception If the file with stability information cannot be read.
code/saf/fm/linear/reader.py
get_stability_info
ExplosiveJam/fickettmodel-reproducibility
1
python
def get_stability_info(self): "Read file with stability info for time series of detonation speed.\n\n Returns\n -------\n eigvals : list\n List with eigenvalues. Each element is a dictionary\n with keys {'growth_rate', 'frequency'}.\n\n Raises\n ------\n Exception\n If the file with stability information cannot be read.\n\n " eigvals = [] fit_file = os.path.join(self._results_dir, 'stability.txt') if (not os.path.isfile(fit_file)): raise ReaderError("Cannot find file 'stability.txt'.") with open(fit_file, 'r') as f: for line in f: if line.startswith('#'): continue if line.startswith('---'): break chunks = line.split() gr = float(chunks[0]) fr = float(chunks[1]) if len(eigvals): prev_eig = eigvals[(- 1)] if (type(prev_eig) is dict): if (fr == eigvals[(- 1)]['frequency']): eig_1 = eigvals.pop() eig_2 = {'growth_rate': gr, 'frequency': fr} eigs = [eig_1, eig_2] eigvals.append(eigs) else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) elif (type(prev_eig) is list): if (fr == prev_eig[(- 1)]['frequency']): eigs = eigvals.pop() eig_2 = {'growth_rate': gr, 'frequency': fr} eigs.append(eig_2) eigvals.append(eigs) else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) else: raise Exception('Cannot parse stability.txt') else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) return eigvals
def get_stability_info(self): "Read file with stability info for time series of detonation speed.\n\n Returns\n -------\n eigvals : list\n List with eigenvalues. Each element is a dictionary\n with keys {'growth_rate', 'frequency'}.\n\n Raises\n ------\n Exception\n If the file with stability information cannot be read.\n\n " eigvals = [] fit_file = os.path.join(self._results_dir, 'stability.txt') if (not os.path.isfile(fit_file)): raise ReaderError("Cannot find file 'stability.txt'.") with open(fit_file, 'r') as f: for line in f: if line.startswith('#'): continue if line.startswith('---'): break chunks = line.split() gr = float(chunks[0]) fr = float(chunks[1]) if len(eigvals): prev_eig = eigvals[(- 1)] if (type(prev_eig) is dict): if (fr == eigvals[(- 1)]['frequency']): eig_1 = eigvals.pop() eig_2 = {'growth_rate': gr, 'frequency': fr} eigs = [eig_1, eig_2] eigvals.append(eigs) else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) elif (type(prev_eig) is list): if (fr == prev_eig[(- 1)]['frequency']): eigs = eigvals.pop() eig_2 = {'growth_rate': gr, 'frequency': fr} eigs.append(eig_2) eigvals.append(eigs) else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) else: raise Exception('Cannot parse stability.txt') else: eig = {'growth_rate': gr, 'frequency': fr} eigvals.append(eig) return eigvals<|docstring|>Read file with stability info for time series of detonation speed. Returns ------- eigvals : list List with eigenvalues. Each element is a dictionary with keys {'growth_rate', 'frequency'}. Raises ------ Exception If the file with stability information cannot be read.<|endoftext|>
de865d5597de4b28ddf01bc23e317ea6c5072d16f12dd8aad90e94f3a876ae5c
def color_output(txt): 'Color system writes.' colored = highlight(str(txt), PythonLexer(), TerminalFormatter()) sys.stdout.write((colored + '\n'))
Color system writes.
mini_matlab/utils.py
color_output
Habu-Kagumba/mini_matlab
0
python
def color_output(txt): colored = highlight(str(txt), PythonLexer(), TerminalFormatter()) sys.stdout.write((colored + '\n'))
def color_output(txt): colored = highlight(str(txt), PythonLexer(), TerminalFormatter()) sys.stdout.write((colored + '\n'))<|docstring|>Color system writes.<|endoftext|>
d59887246797b263b7731073578fd56feffd83833406763e3302c8fbf66ec128
def validate_primary_email(self, user): '\n Sends a persistent error notification.\n\n Checks if the user has a primary email or if the primary email\n is verified or not. Sends a persistent error notification if\n either of the condition is False.\n ' email_qs = user.emailaddress_set.filter(primary=True) email = email_qs.first() if ((not email) or (not email.verified)): notification = EmailConfirmNotification(user=user, success=False) notification.send()
Sends a persistent error notification. Checks if the user has a primary email or if the primary email is verified or not. Sends a persistent error notification if either of the condition is False.
readthedocs/projects/views/private.py
validate_primary_email
Witchie/readthedocs.org
2
python
def validate_primary_email(self, user): '\n Sends a persistent error notification.\n\n Checks if the user has a primary email or if the primary email\n is verified or not. Sends a persistent error notification if\n either of the condition is False.\n ' email_qs = user.emailaddress_set.filter(primary=True) email = email_qs.first() if ((not email) or (not email.verified)): notification = EmailConfirmNotification(user=user, success=False) notification.send()
def validate_primary_email(self, user): '\n Sends a persistent error notification.\n\n Checks if the user has a primary email or if the primary email\n is verified or not. Sends a persistent error notification if\n either of the condition is False.\n ' email_qs = user.emailaddress_set.filter(primary=True) email = email_qs.first() if ((not email) or (not email.verified)): notification = EmailConfirmNotification(user=user, success=False) notification.send()<|docstring|>Sends a persistent error notification. Checks if the user has a primary email or if the primary email is verified or not. Sends a persistent error notification if either of the condition is False.<|endoftext|>
e8f440a78b34f4574f6a09a1b29303639a77e237b948ce526a702113efa2d7a9
def get_form_kwargs(self, step=None): 'Get args to pass into form instantiation.' kwargs = {} kwargs['user'] = self.request.user if (step == 'basics'): kwargs['show_advanced'] = True return kwargs
Get args to pass into form instantiation.
readthedocs/projects/views/private.py
get_form_kwargs
Witchie/readthedocs.org
2
python
def get_form_kwargs(self, step=None): kwargs = {} kwargs['user'] = self.request.user if (step == 'basics'): kwargs['show_advanced'] = True return kwargs
def get_form_kwargs(self, step=None): kwargs = {} kwargs['user'] = self.request.user if (step == 'basics'): kwargs['show_advanced'] = True return kwargs<|docstring|>Get args to pass into form instantiation.<|endoftext|>
8e2eacf747b15e9483496cb1a665f867d9e7388e809c1135368bf2c5f7e6510d
def get_template_names(self): 'Return template names based on step name.' return 'projects/import_{}.html'.format(self.steps.current)
Return template names based on step name.
readthedocs/projects/views/private.py
get_template_names
Witchie/readthedocs.org
2
python
def get_template_names(self): return 'projects/import_{}.html'.format(self.steps.current)
def get_template_names(self): return 'projects/import_{}.html'.format(self.steps.current)<|docstring|>Return template names based on step name.<|endoftext|>
f271f553a50e5f773fef6556a30f118fd4e97fbe6157d9ac5590c07f93252ff2
def done(self, form_list, **kwargs): "\n Save form data as object instance.\n\n Don't save form data directly, instead bypass documentation building and\n other side effects for now, by signalling a save without commit. Then,\n finish by added the members to the project and saving.\n " form_data = self.get_all_cleaned_data() extra_fields = ProjectExtraForm.Meta.fields basics_form = list(form_list)[0] project = basics_form.save() tags = form_data.pop('tags', []) for (field, value) in list(form_data.items()): if (field in extra_fields): setattr(project, field, value) project.save() self.finish_import_project(self.request, project, tags) return HttpResponseRedirect(reverse('projects_detail', args=[project.slug]))
Save form data as object instance. Don't save form data directly, instead bypass documentation building and other side effects for now, by signalling a save without commit. Then, finish by added the members to the project and saving.
readthedocs/projects/views/private.py
done
Witchie/readthedocs.org
2
python
def done(self, form_list, **kwargs): "\n Save form data as object instance.\n\n Don't save form data directly, instead bypass documentation building and\n other side effects for now, by signalling a save without commit. Then,\n finish by added the members to the project and saving.\n " form_data = self.get_all_cleaned_data() extra_fields = ProjectExtraForm.Meta.fields basics_form = list(form_list)[0] project = basics_form.save() tags = form_data.pop('tags', []) for (field, value) in list(form_data.items()): if (field in extra_fields): setattr(project, field, value) project.save() self.finish_import_project(self.request, project, tags) return HttpResponseRedirect(reverse('projects_detail', args=[project.slug]))
def done(self, form_list, **kwargs): "\n Save form data as object instance.\n\n Don't save form data directly, instead bypass documentation building and\n other side effects for now, by signalling a save without commit. Then,\n finish by added the members to the project and saving.\n " form_data = self.get_all_cleaned_data() extra_fields = ProjectExtraForm.Meta.fields basics_form = list(form_list)[0] project = basics_form.save() tags = form_data.pop('tags', []) for (field, value) in list(form_data.items()): if (field in extra_fields): setattr(project, field, value) project.save() self.finish_import_project(self.request, project, tags) return HttpResponseRedirect(reverse('projects_detail', args=[project.slug]))<|docstring|>Save form data as object instance. Don't save form data directly, instead bypass documentation building and other side effects for now, by signalling a save without commit. Then, finish by added the members to the project and saving.<|endoftext|>
06cc0cd73b6dda0b45cac7d11a5d2e3fdc026f19c218adf6358dda0777c39905
def is_advanced(self): 'Determine if the user selected the `show advanced` field.' data = (self.get_cleaned_data_for_step('basics') or {}) return data.get('advanced', True)
Determine if the user selected the `show advanced` field.
readthedocs/projects/views/private.py
is_advanced
Witchie/readthedocs.org
2
python
def is_advanced(self): data = (self.get_cleaned_data_for_step('basics') or {}) return data.get('advanced', True)
def is_advanced(self): data = (self.get_cleaned_data_for_step('basics') or {}) return data.get('advanced', True)<|docstring|>Determine if the user selected the `show advanced` field.<|endoftext|>
9d8da45789f2b8d71511a8c62e3ca47688553a346ff679478c453a2e192d9185
def get(self, request, *args, **kwargs): 'Process link request as a form post to the project import form.' self.request = request self.args = args self.kwargs = kwargs data = self.get_form_data() project = Project.objects.for_admin_user(request.user).filter(repo=data['repo']).first() if (project is not None): messages.success(request, _('The demo project is already imported!')) else: kwargs = self.get_form_kwargs() form = self.form_class(data=data, **kwargs) if form.is_valid(): project = form.save() project.save() self.trigger_initial_build(project, request.user) messages.success(request, _('Your demo project is currently being imported')) else: messages.error(request, _('There was a problem adding the demo project')) return HttpResponseRedirect(reverse('projects_dashboard')) return HttpResponseRedirect(reverse('projects_detail', args=[project.slug]))
Process link request as a form post to the project import form.
readthedocs/projects/views/private.py
get
Witchie/readthedocs.org
2
python
def get(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs data = self.get_form_data() project = Project.objects.for_admin_user(request.user).filter(repo=data['repo']).first() if (project is not None): messages.success(request, _('The demo project is already imported!')) else: kwargs = self.get_form_kwargs() form = self.form_class(data=data, **kwargs) if form.is_valid(): project = form.save() project.save() self.trigger_initial_build(project, request.user) messages.success(request, _('Your demo project is currently being imported')) else: messages.error(request, _('There was a problem adding the demo project')) return HttpResponseRedirect(reverse('projects_dashboard')) return HttpResponseRedirect(reverse('projects_detail', args=[project.slug]))
def get(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs data = self.get_form_data() project = Project.objects.for_admin_user(request.user).filter(repo=data['repo']).first() if (project is not None): messages.success(request, _('The demo project is already imported!')) else: kwargs = self.get_form_kwargs() form = self.form_class(data=data, **kwargs) if form.is_valid(): project = form.save() project.save() self.trigger_initial_build(project, request.user) messages.success(request, _('Your demo project is currently being imported')) else: messages.error(request, _('There was a problem adding the demo project')) return HttpResponseRedirect(reverse('projects_dashboard')) return HttpResponseRedirect(reverse('projects_detail', args=[project.slug]))<|docstring|>Process link request as a form post to the project import form.<|endoftext|>
79fa429a9d70c9c83ce4c72ea7d16edad8d8bc8f5b67ad8f5b1982ea3af5b335
def get_form_data(self): 'Get form data to post to import form.' return {'name': '{}-demo'.format(self.request.user.username), 'repo_type': 'git', 'repo': 'https://github.com/readthedocs/template.git'}
Get form data to post to import form.
readthedocs/projects/views/private.py
get_form_data
Witchie/readthedocs.org
2
python
def get_form_data(self): return {'name': '{}-demo'.format(self.request.user.username), 'repo_type': 'git', 'repo': 'https://github.com/readthedocs/template.git'}
def get_form_data(self): return {'name': '{}-demo'.format(self.request.user.username), 'repo_type': 'git', 'repo': 'https://github.com/readthedocs/template.git'}<|docstring|>Get form data to post to import form.<|endoftext|>
43fef669896a00ffab492721548fcb2455497b5bf85f6e00acb7d43ec27ce8e4
def get_form_kwargs(self): 'Form kwargs passed in during instantiation.' return {'user': self.request.user}
Form kwargs passed in during instantiation.
readthedocs/projects/views/private.py
get_form_kwargs
Witchie/readthedocs.org
2
python
def get_form_kwargs(self): return {'user': self.request.user}
def get_form_kwargs(self): return {'user': self.request.user}<|docstring|>Form kwargs passed in during instantiation.<|endoftext|>
9150718c18d33eb5cdb9782d6e581037129e77d1e2d5a9442df16ab595d119a3
def trigger_initial_build(self, project, user): '\n Trigger initial build.\n\n Allow to override the behavior from outside.\n ' return trigger_build(project)
Trigger initial build. Allow to override the behavior from outside.
readthedocs/projects/views/private.py
trigger_initial_build
Witchie/readthedocs.org
2
python
def trigger_initial_build(self, project, user): '\n Trigger initial build.\n\n Allow to override the behavior from outside.\n ' return trigger_build(project)
def trigger_initial_build(self, project, user): '\n Trigger initial build.\n\n Allow to override the behavior from outside.\n ' return trigger_build(project)<|docstring|>Trigger initial build. Allow to override the behavior from outside.<|endoftext|>
381e4a32bf24135a290cab0ed0874370475048745c8c0a5c6f3cb263b44fb176
def get(self, request, *args, **kwargs): '\n Display list of repositories to import.\n\n Adds a warning to the listing if any of the accounts connected for the\n user are not supported accounts.\n ' deprecated_accounts = SocialAccount.objects.filter(user=self.request.user).exclude(provider__in=[service.adapter.provider_id for service in registry]) for account in deprecated_accounts: provider_account = account.get_provider_account() messages.error(request, mark_safe(_('There is a problem with your {service} account, try reconnecting your account on your <a href="{url}">connected services page</a>.').format(service=provider_account.get_brand()['name'], url=reverse('socialaccount_connections')))) return super().get(request, *args, **kwargs)
Display list of repositories to import. Adds a warning to the listing if any of the accounts connected for the user are not supported accounts.
readthedocs/projects/views/private.py
get
Witchie/readthedocs.org
2
python
def get(self, request, *args, **kwargs): '\n Display list of repositories to import.\n\n Adds a warning to the listing if any of the accounts connected for the\n user are not supported accounts.\n ' deprecated_accounts = SocialAccount.objects.filter(user=self.request.user).exclude(provider__in=[service.adapter.provider_id for service in registry]) for account in deprecated_accounts: provider_account = account.get_provider_account() messages.error(request, mark_safe(_('There is a problem with your {service} account, try reconnecting your account on your <a href="{url}">connected services page</a>.').format(service=provider_account.get_brand()['name'], url=reverse('socialaccount_connections')))) return super().get(request, *args, **kwargs)
def get(self, request, *args, **kwargs): '\n Display list of repositories to import.\n\n Adds a warning to the listing if any of the accounts connected for the\n user are not supported accounts.\n ' deprecated_accounts = SocialAccount.objects.filter(user=self.request.user).exclude(provider__in=[service.adapter.provider_id for service in registry]) for account in deprecated_accounts: provider_account = account.get_provider_account() messages.error(request, mark_safe(_('There is a problem with your {service} account, try reconnecting your account on your <a href="{url}">connected services page</a>.').format(service=provider_account.get_brand()['name'], url=reverse('socialaccount_connections')))) return super().get(request, *args, **kwargs)<|docstring|>Display list of repositories to import. Adds a warning to the listing if any of the accounts connected for the user are not supported accounts.<|endoftext|>
8607a3093cae43d420099007d9b8422682be1e20f0c0d85614e2b41866408455
def get_integration(self): 'Return project integration determined by url kwarg.' if (self.integration_url_field not in self.kwargs): return None return get_object_or_404(Integration, pk=self.kwargs[self.integration_url_field], project=self.get_project())
Return project integration determined by url kwarg.
readthedocs/projects/views/private.py
get_integration
Witchie/readthedocs.org
2
python
def get_integration(self): if (self.integration_url_field not in self.kwargs): return None return get_object_or_404(Integration, pk=self.kwargs[self.integration_url_field], project=self.get_project())
def get_integration(self): if (self.integration_url_field not in self.kwargs): return None return get_object_or_404(Integration, pk=self.kwargs[self.integration_url_field], project=self.get_project())<|docstring|>Return project integration determined by url kwarg.<|endoftext|>
5500b6fe08d2a519a05320a1bb800e4dc9eb8a27bbb65a067dbaaffaacde9c87
def _search_analytics_csv_data(self): 'Generate raw csv data of search queries.' project = self.get_project() now = timezone.now().date() last_3_month = (now - timezone.timedelta(days=90)) data = SearchQuery.objects.filter(project=project, created__date__gte=last_3_month, created__date__lte=now).order_by('-created').values_list('created', 'query', 'total_results') file_name = '{project_slug}_from_{start}_to_{end}.csv'.format(project_slug=project.slug, start=timezone.datetime.strftime(last_3_month, '%Y-%m-%d'), end=timezone.datetime.strftime(now, '%Y-%m-%d')) file_name = '-'.join([text for text in file_name.split() if text]) csv_data = ([timezone.datetime.strftime(time, '%Y-%m-%d %H:%M:%S'), query, total_results] for (time, query, total_results) in data) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in csv_data), content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="{file_name}"' return response
Generate raw csv data of search queries.
readthedocs/projects/views/private.py
_search_analytics_csv_data
Witchie/readthedocs.org
2
python
def _search_analytics_csv_data(self): project = self.get_project() now = timezone.now().date() last_3_month = (now - timezone.timedelta(days=90)) data = SearchQuery.objects.filter(project=project, created__date__gte=last_3_month, created__date__lte=now).order_by('-created').values_list('created', 'query', 'total_results') file_name = '{project_slug}_from_{start}_to_{end}.csv'.format(project_slug=project.slug, start=timezone.datetime.strftime(last_3_month, '%Y-%m-%d'), end=timezone.datetime.strftime(now, '%Y-%m-%d')) file_name = '-'.join([text for text in file_name.split() if text]) csv_data = ([timezone.datetime.strftime(time, '%Y-%m-%d %H:%M:%S'), query, total_results] for (time, query, total_results) in data) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in csv_data), content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="{file_name}"' return response
def _search_analytics_csv_data(self): project = self.get_project() now = timezone.now().date() last_3_month = (now - timezone.timedelta(days=90)) data = SearchQuery.objects.filter(project=project, created__date__gte=last_3_month, created__date__lte=now).order_by('-created').values_list('created', 'query', 'total_results') file_name = '{project_slug}_from_{start}_to_{end}.csv'.format(project_slug=project.slug, start=timezone.datetime.strftime(last_3_month, '%Y-%m-%d'), end=timezone.datetime.strftime(now, '%Y-%m-%d')) file_name = '-'.join([text for text in file_name.split() if text]) csv_data = ([timezone.datetime.strftime(time, '%Y-%m-%d %H:%M:%S'), query, total_results] for (time, query, total_results) in data) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in csv_data), content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="{file_name}"' return response<|docstring|>Generate raw csv data of search queries.<|endoftext|>
5e09156d1d18dcbb10bad3b76240344e5dc7df833fcfac913e21a75f0c5dd9b4
def _is_enabled(self, project): 'Should we show search analytics for this project?' return True
Should we show search analytics for this project?
readthedocs/projects/views/private.py
_is_enabled
Witchie/readthedocs.org
2
python
def _is_enabled(self, project): return True
def _is_enabled(self, project): return True<|docstring|>Should we show search analytics for this project?<|endoftext|>
80ca32f29b387453975147e0baca14a523cad1e6d56f8b06559bfe638fb0b24c
def _is_enabled(self, project): 'Should we show traffic analytics for this project?' return project.has_feature(Feature.STORE_PAGEVIEWS)
Should we show traffic analytics for this project?
readthedocs/projects/views/private.py
_is_enabled
Witchie/readthedocs.org
2
python
def _is_enabled(self, project): return project.has_feature(Feature.STORE_PAGEVIEWS)
def _is_enabled(self, project): return project.has_feature(Feature.STORE_PAGEVIEWS)<|docstring|>Should we show traffic analytics for this project?<|endoftext|>
25609177920874ab5b5ca746ab52193e1104e109913dcfce645cd0743fb5da93
def __init__(self, growth_rate: int, structure: list, num_init_features: int, bn_size: int, drop_rate: float, num_classes: int): "\n :param growth_rate: number of filter to add each layer (noted as 'k' in the paper)\n :param structure: how many layers in each pooling block - sequentially\n :param num_init_features: the number of filters to learn in the first convolutional layer\n :param bn_size: multiplicative factor for the number of bottle neck layers\n (i.e. bn_size * k featurs in the bottleneck)\n :param drop_rate: dropout rate after each dense layer\n :param num_classes: number of classes in the classification task\n " super(DenseNet, self).__init__() self.features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)), ('norm0', nn.BatchNorm2d(num_init_features)), ('relu0', nn.ReLU(inplace=True)), ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))])) num_features = num_init_features for (i, num_layers) in enumerate(structure): block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate) self.features.add_module(('denseblock%d' % (i + 1)), block) num_features = (num_features + (num_layers * growth_rate)) if (i != (len(structure) - 1)): trans = _Transition(num_input_features=num_features, num_output_features=(num_features // 2)) self.features.add_module(('transition%d' % (i + 1)), trans) num_features = (num_features // 2) self.features.add_module('norm5', nn.BatchNorm2d(num_features)) self.classifier = nn.Linear(num_features, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.constant_(m.bias, 0)
:param growth_rate: number of filter to add each layer (noted as 'k' in the paper) :param structure: how many layers in each pooling block - sequentially :param num_init_features: the number of filters to learn in the first convolutional layer :param bn_size: multiplicative factor for the number of bottle neck layers (i.e. bn_size * k featurs in the bottleneck) :param drop_rate: dropout rate after each dense layer :param num_classes: number of classes in the classification task
src/super_gradients/training/models/classification_models/densenet.py
__init__
Deci-AI/super-gradients
308
python
def __init__(self, growth_rate: int, structure: list, num_init_features: int, bn_size: int, drop_rate: float, num_classes: int): "\n :param growth_rate: number of filter to add each layer (noted as 'k' in the paper)\n :param structure: how many layers in each pooling block - sequentially\n :param num_init_features: the number of filters to learn in the first convolutional layer\n :param bn_size: multiplicative factor for the number of bottle neck layers\n (i.e. bn_size * k featurs in the bottleneck)\n :param drop_rate: dropout rate after each dense layer\n :param num_classes: number of classes in the classification task\n " super(DenseNet, self).__init__() self.features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)), ('norm0', nn.BatchNorm2d(num_init_features)), ('relu0', nn.ReLU(inplace=True)), ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))])) num_features = num_init_features for (i, num_layers) in enumerate(structure): block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate) self.features.add_module(('denseblock%d' % (i + 1)), block) num_features = (num_features + (num_layers * growth_rate)) if (i != (len(structure) - 1)): trans = _Transition(num_input_features=num_features, num_output_features=(num_features // 2)) self.features.add_module(('transition%d' % (i + 1)), trans) num_features = (num_features // 2) self.features.add_module('norm5', nn.BatchNorm2d(num_features)) self.classifier = nn.Linear(num_features, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.constant_(m.bias, 0)
def __init__(self, growth_rate: int, structure: list, num_init_features: int, bn_size: int, drop_rate: float, num_classes: int): "\n :param growth_rate: number of filter to add each layer (noted as 'k' in the paper)\n :param structure: how many layers in each pooling block - sequentially\n :param num_init_features: the number of filters to learn in the first convolutional layer\n :param bn_size: multiplicative factor for the number of bottle neck layers\n (i.e. bn_size * k featurs in the bottleneck)\n :param drop_rate: dropout rate after each dense layer\n :param num_classes: number of classes in the classification task\n " super(DenseNet, self).__init__() self.features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)), ('norm0', nn.BatchNorm2d(num_init_features)), ('relu0', nn.ReLU(inplace=True)), ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))])) num_features = num_init_features for (i, num_layers) in enumerate(structure): block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate) self.features.add_module(('denseblock%d' % (i + 1)), block) num_features = (num_features + (num_layers * growth_rate)) if (i != (len(structure) - 1)): trans = _Transition(num_input_features=num_features, num_output_features=(num_features // 2)) self.features.add_module(('transition%d' % (i + 1)), trans) num_features = (num_features // 2) self.features.add_module('norm5', nn.BatchNorm2d(num_features)) self.classifier = nn.Linear(num_features, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.constant_(m.bias, 0)<|docstring|>:param growth_rate: number of filter to add each layer (noted as 'k' in the paper) :param structure: how many layers in each pooling block - sequentially :param num_init_features: the number of filters to learn in the first convolutional layer :param bn_size: multiplicative factor for the number of bottle neck layers (i.e. bn_size * k featurs in the bottleneck) :param drop_rate: dropout rate after each dense layer :param num_classes: number of classes in the classification task<|endoftext|>
e6b83ea8bbd6daf5b124673e5341b4a153a6499a04d094188d0e4297048346c4
def authenticate(): 'Function for handling Twitter Authentication. See config.py and docker-compose.yml for details.' auth = OAuthHandler(config.API_KEY, config.API_SECRET) auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET) return auth
Function for handling Twitter Authentication. See config.py and docker-compose.yml for details.
tweet_collector/tweet_collector.py
authenticate
ai-aksoyoglu/06_Docker_Pipeline_TweeterAPI
0
python
def authenticate(): auth = OAuthHandler(config.API_KEY, config.API_SECRET) auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET) return auth
def authenticate(): auth = OAuthHandler(config.API_KEY, config.API_SECRET) auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET) return auth<|docstring|>Function for handling Twitter Authentication. See config.py and docker-compose.yml for details.<|endoftext|>
0e183747947e263c98c63e2c1a96e82c77dbe8106079e38609f3e631e3206552
def on_data(self, data): 'Whatever we put in this method defines what is done with every single tweet as it is intercepted in real-time' client = pymongo.MongoClient(host='mongodb') db = client.tweets collection = db.tweet_data t = json.loads(data) tweet = {'username': t['user']['screen_name'], 'text': t['text'], 'timestamp': t['created_at']} logging.critical(f''' TWEET INCOMING: {tweet['text']} ''') logging.critical('-----Tweet written into MongoDB-----') collection.insert_one(tweet) logging.critical(str(datetime.now())) logging.critical('----------\n') time.sleep(3)
Whatever we put in this method defines what is done with every single tweet as it is intercepted in real-time
tweet_collector/tweet_collector.py
on_data
ai-aksoyoglu/06_Docker_Pipeline_TweeterAPI
0
python
def on_data(self, data): client = pymongo.MongoClient(host='mongodb') db = client.tweets collection = db.tweet_data t = json.loads(data) tweet = {'username': t['user']['screen_name'], 'text': t['text'], 'timestamp': t['created_at']} logging.critical(f' TWEET INCOMING: {tweet['text']} ') logging.critical('-----Tweet written into MongoDB-----') collection.insert_one(tweet) logging.critical(str(datetime.now())) logging.critical('----------\n') time.sleep(3)
def on_data(self, data): client = pymongo.MongoClient(host='mongodb') db = client.tweets collection = db.tweet_data t = json.loads(data) tweet = {'username': t['user']['screen_name'], 'text': t['text'], 'timestamp': t['created_at']} logging.critical(f' TWEET INCOMING: {tweet['text']} ') logging.critical('-----Tweet written into MongoDB-----') collection.insert_one(tweet) logging.critical(str(datetime.now())) logging.critical('----------\n') time.sleep(3)<|docstring|>Whatever we put in this method defines what is done with every single tweet as it is intercepted in real-time<|endoftext|>
a684885c538fe7e1ab2bb1633764709f5a7d43bacfa392cc92c5eedac8a2a87b
def smooth(y: np.ndarray, box_pts: int) -> np.ndarray: '\n Smooths the points in y with a weighted average.\n\n Parameters\n ----------------\n y\n Points\n box_pts\n Size of the weighted average\n\n Returns\n ----------------\n y_smooth\n Smoothened y\n ' box = (np.ones(box_pts) / box_pts) y_smooth = np.convolve(y, box, mode='same') return y_smooth
Smooths the points in y with a weighted average. Parameters ---------------- y Points box_pts Size of the weighted average Returns ---------------- y_smooth Smoothened y
ws2122-lspm/Lib/site-packages/pm4py/algo/transformation/log_to_features/util/locally_linear_embedding.py
smooth
Malekhy/ws2122-lspm
1
python
def smooth(y: np.ndarray, box_pts: int) -> np.ndarray: '\n Smooths the points in y with a weighted average.\n\n Parameters\n ----------------\n y\n Points\n box_pts\n Size of the weighted average\n\n Returns\n ----------------\n y_smooth\n Smoothened y\n ' box = (np.ones(box_pts) / box_pts) y_smooth = np.convolve(y, box, mode='same') return y_smooth
def smooth(y: np.ndarray, box_pts: int) -> np.ndarray: '\n Smooths the points in y with a weighted average.\n\n Parameters\n ----------------\n y\n Points\n box_pts\n Size of the weighted average\n\n Returns\n ----------------\n y_smooth\n Smoothened y\n ' box = (np.ones(box_pts) / box_pts) y_smooth = np.convolve(y, box, mode='same') return y_smooth<|docstring|>Smooths the points in y with a weighted average. Parameters ---------------- y Points box_pts Size of the weighted average Returns ---------------- y_smooth Smoothened y<|endoftext|>
8775c0c3e29cff0d7da624e68d8af6ce2b05fca84a051990e49ecea5153bff88
def apply(log: EventLog, parameters: Optional[Dict[(str, Any)]]=None) -> Tuple[(List[datetime], np.ndarray)]: '\n Analyse the evolution of the features over the time using a locally linear embedding.\n\n Parameters\n -----------------\n log\n Event log\n parameters\n Variant-specific parameters, including:\n - Parameters.ACTIVITY_KEY => the activity key\n - Parameters.TIMESTAMP_KEY => the timestamp key\n - Parameters.CASE_ID_KEY => the case ID key\n\n Returns\n ----------------\n x\n Date attributes (starting points of the cases)\n y\n Deviation from the standard behavior (higher absolute values of y signal a higher deviation\n from the standard behavior)\n ' if (parameters is None): parameters = {} activity_key = exec_utils.get_param_value(Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY) timestamp_key = exec_utils.get_param_value(Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY) if (type(log) is pd.DataFrame): case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME) log = log[[case_id_key, activity_key, timestamp_key]] log = log_converter.apply(log, parameters=parameters) log = sorting.sort_timestamp(log, timestamp_key) x = [trace[0][timestamp_key] for trace in log] (data, feature_names) = log_to_features.apply(log, parameters={'str_ev_attr': [activity_key], 'str_evsucc_attr': [activity_key]}) tsne = LocallyLinearEmbedding(n_components=1) data = tsne.fit_transform(data) data = np.ndarray.flatten(data) y = data smooth_amount = (1 + math.floor(math.sqrt(len(y)))) y = smooth(y, smooth_amount) return (x, y)
Analyse the evolution of the features over the time using a locally linear embedding. Parameters ----------------- log Event log parameters Variant-specific parameters, including: - Parameters.ACTIVITY_KEY => the activity key - Parameters.TIMESTAMP_KEY => the timestamp key - Parameters.CASE_ID_KEY => the case ID key Returns ---------------- x Date attributes (starting points of the cases) y Deviation from the standard behavior (higher absolute values of y signal a higher deviation from the standard behavior)
ws2122-lspm/Lib/site-packages/pm4py/algo/transformation/log_to_features/util/locally_linear_embedding.py
apply
Malekhy/ws2122-lspm
1
python
def apply(log: EventLog, parameters: Optional[Dict[(str, Any)]]=None) -> Tuple[(List[datetime], np.ndarray)]: '\n Analyse the evolution of the features over the time using a locally linear embedding.\n\n Parameters\n -----------------\n log\n Event log\n parameters\n Variant-specific parameters, including:\n - Parameters.ACTIVITY_KEY => the activity key\n - Parameters.TIMESTAMP_KEY => the timestamp key\n - Parameters.CASE_ID_KEY => the case ID key\n\n Returns\n ----------------\n x\n Date attributes (starting points of the cases)\n y\n Deviation from the standard behavior (higher absolute values of y signal a higher deviation\n from the standard behavior)\n ' if (parameters is None): parameters = {} activity_key = exec_utils.get_param_value(Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY) timestamp_key = exec_utils.get_param_value(Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY) if (type(log) is pd.DataFrame): case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME) log = log[[case_id_key, activity_key, timestamp_key]] log = log_converter.apply(log, parameters=parameters) log = sorting.sort_timestamp(log, timestamp_key) x = [trace[0][timestamp_key] for trace in log] (data, feature_names) = log_to_features.apply(log, parameters={'str_ev_attr': [activity_key], 'str_evsucc_attr': [activity_key]}) tsne = LocallyLinearEmbedding(n_components=1) data = tsne.fit_transform(data) data = np.ndarray.flatten(data) y = data smooth_amount = (1 + math.floor(math.sqrt(len(y)))) y = smooth(y, smooth_amount) return (x, y)
def apply(log: EventLog, parameters: Optional[Dict[(str, Any)]]=None) -> Tuple[(List[datetime], np.ndarray)]: '\n Analyse the evolution of the features over the time using a locally linear embedding.\n\n Parameters\n -----------------\n log\n Event log\n parameters\n Variant-specific parameters, including:\n - Parameters.ACTIVITY_KEY => the activity key\n - Parameters.TIMESTAMP_KEY => the timestamp key\n - Parameters.CASE_ID_KEY => the case ID key\n\n Returns\n ----------------\n x\n Date attributes (starting points of the cases)\n y\n Deviation from the standard behavior (higher absolute values of y signal a higher deviation\n from the standard behavior)\n ' if (parameters is None): parameters = {} activity_key = exec_utils.get_param_value(Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY) timestamp_key = exec_utils.get_param_value(Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY) if (type(log) is pd.DataFrame): case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME) log = log[[case_id_key, activity_key, timestamp_key]] log = log_converter.apply(log, parameters=parameters) log = sorting.sort_timestamp(log, timestamp_key) x = [trace[0][timestamp_key] for trace in log] (data, feature_names) = log_to_features.apply(log, parameters={'str_ev_attr': [activity_key], 'str_evsucc_attr': [activity_key]}) tsne = LocallyLinearEmbedding(n_components=1) data = tsne.fit_transform(data) data = np.ndarray.flatten(data) y = data smooth_amount = (1 + math.floor(math.sqrt(len(y)))) y = smooth(y, smooth_amount) return (x, y)<|docstring|>Analyse the evolution of the features over the time using a locally linear embedding. Parameters ----------------- log Event log parameters Variant-specific parameters, including: - Parameters.ACTIVITY_KEY => the activity key - Parameters.TIMESTAMP_KEY => the timestamp key - Parameters.CASE_ID_KEY => the case ID key Returns ---------------- x Date attributes (starting points of the cases) y Deviation from the standard behavior (higher absolute values of y signal a higher deviation from the standard behavior)<|endoftext|>
de3196f5c743da3daf2a035ca1b9ad97c7fbebc603045c31c9312b3ddd48f625
def print_all_subsystems(destination): '\n :param destination: destination directory to output files to\n ' dir_name = 'dot_subsystems' if os.path.isdir(dir_name): shutil.rmtree(dir_name) os.makedirs(dir_name) for graph_text in subgraph_texts: f_name = graph_text.strip().split(os.linesep)[0].split(' ')[1][7:] f_name_with_dir = os.path.join(dir_name, (f_name + '.dot')) f = open(f_name_with_dir, 'wb') f.write(str.encode((('digraph{' + os.linesep) + '\t graph [splines=ortho]'))) f.write(str.encode(graph_text)) f.write(str.encode('}//end digraph')) f.close() os.chdir(((os.getcwd() + os.sep) + dir_name)) output_as(f_name, OUTPUT_FORMAT, destination) os.chdir('..')
:param destination: destination directory to output files to
Tools/DiagramGenerator/dotGenerator.py
print_all_subsystems
shastrihm/BrainGrid
0
python
def print_all_subsystems(destination): '\n \n ' dir_name = 'dot_subsystems' if os.path.isdir(dir_name): shutil.rmtree(dir_name) os.makedirs(dir_name) for graph_text in subgraph_texts: f_name = graph_text.strip().split(os.linesep)[0].split(' ')[1][7:] f_name_with_dir = os.path.join(dir_name, (f_name + '.dot')) f = open(f_name_with_dir, 'wb') f.write(str.encode((('digraph{' + os.linesep) + '\t graph [splines=ortho]'))) f.write(str.encode(graph_text)) f.write(str.encode('}//end digraph')) f.close() os.chdir(((os.getcwd() + os.sep) + dir_name)) output_as(f_name, OUTPUT_FORMAT, destination) os.chdir('..')
def print_all_subsystems(destination): '\n \n ' dir_name = 'dot_subsystems' if os.path.isdir(dir_name): shutil.rmtree(dir_name) os.makedirs(dir_name) for graph_text in subgraph_texts: f_name = graph_text.strip().split(os.linesep)[0].split(' ')[1][7:] f_name_with_dir = os.path.join(dir_name, (f_name + '.dot')) f = open(f_name_with_dir, 'wb') f.write(str.encode((('digraph{' + os.linesep) + '\t graph [splines=ortho]'))) f.write(str.encode(graph_text)) f.write(str.encode('}//end digraph')) f.close() os.chdir(((os.getcwd() + os.sep) + dir_name)) output_as(f_name, OUTPUT_FORMAT, destination) os.chdir('..')<|docstring|>:param destination: destination directory to output files to<|endoftext|>
0a632326a03189124828ed95c693a6f0dfee07b6a74d57d9d06c8ffc1c624a4a
def print_subgraph(dot_file, sub_name, sub, behavior='d'): "\n Writes the given subgraph to the given file.\n :param dot_file: The file to write to\n :param sub_name: The subgraph's name\n :param sub: The subgraph to print\n :param behavior: 'd' = dot_file; 'o' = sys_overview; 'b' = block_file\n :return: Nothing\n " to_print = (('' + os.linesep) + os.linesep) if (len(sub) is 1): to_print += ((('\tsubgraph ' + sub_name) + ' {') + os.linesep) else: to_print += ((('\tsubgraph cluster' + sub_name) + ' {') + os.linesep) color = sub[0].get('color') subsystem_color_map[sub_name] = color subsystem_color_map_inverse[color] = sub_name if (color is not None): to_print += ('\t\tstyle = rounded' + os.linesep) to_print += (('\t\tbgcolor = ' + lightgray) + os.linesep) to_print += (('\t\tcolor = ' + color) + os.linesep) to_print += (((('\t\tnode [shape = record, color = ' + color) + '];') + os.linesep) + os.linesep) else: to_print += ((('\t\tnode [shape = record];' + os.linesep) + os.linesep) + os.linesep) sub = sorted(sub, key=(lambda nodeInfo: nodeInfo['name'])) for c in sub: to_print += (((('\t\t' + c.get('name')) + '[label = ') + c.get('name')) + ', style = filled') to_print += ('];' + os.linesep) if ((behavior == 'b') or (behavior == 'o') or ((behavior == 'd') and (len(sub) > 1))): if (sub[0].get('color') is not None): to_print += (((('\t\t' + sub_name) + '[label =< <B> ') + sub_name) + '</B>>, style = bold, fillcolor = white, style = filled') else: to_print += (((('\t\t' + sub_name) + '[label = ') + sub_name) + ', style = filled') to_print += ('];' + os.linesep) names_in_this_subgraph = [d.get('name') for d in sub] subgraph_inheritance = [tup for tup in inheritance if ((tup[0] in names_in_this_subgraph) and (tup[1] in names_in_this_subgraph))] subgraph_includes = [tup for tup in includes if ((tup[0] in names_in_this_subgraph) and (tup[1] in names_in_this_subgraph) and (tup not in subgraph_inheritance))] layout = print_subgraph_layout(subgraph_inheritance, subgraph_includes, behavior) to_print += layout to_print += (('\t}//end subgraph ' + sub_name) + os.linesep) dot_file.write(str.encode(to_print)) if (behavior == 'd'): if (len(sub) > 1): subgraph_texts.append(to_print)
Writes the given subgraph to the given file. :param dot_file: The file to write to :param sub_name: The subgraph's name :param sub: The subgraph to print :param behavior: 'd' = dot_file; 'o' = sys_overview; 'b' = block_file :return: Nothing
Tools/DiagramGenerator/dotGenerator.py
print_subgraph
shastrihm/BrainGrid
0
python
def print_subgraph(dot_file, sub_name, sub, behavior='d'): "\n Writes the given subgraph to the given file.\n :param dot_file: The file to write to\n :param sub_name: The subgraph's name\n :param sub: The subgraph to print\n :param behavior: 'd' = dot_file; 'o' = sys_overview; 'b' = block_file\n :return: Nothing\n " to_print = (( + os.linesep) + os.linesep) if (len(sub) is 1): to_print += ((('\tsubgraph ' + sub_name) + ' {') + os.linesep) else: to_print += ((('\tsubgraph cluster' + sub_name) + ' {') + os.linesep) color = sub[0].get('color') subsystem_color_map[sub_name] = color subsystem_color_map_inverse[color] = sub_name if (color is not None): to_print += ('\t\tstyle = rounded' + os.linesep) to_print += (('\t\tbgcolor = ' + lightgray) + os.linesep) to_print += (('\t\tcolor = ' + color) + os.linesep) to_print += (((('\t\tnode [shape = record, color = ' + color) + '];') + os.linesep) + os.linesep) else: to_print += ((('\t\tnode [shape = record];' + os.linesep) + os.linesep) + os.linesep) sub = sorted(sub, key=(lambda nodeInfo: nodeInfo['name'])) for c in sub: to_print += (((('\t\t' + c.get('name')) + '[label = ') + c.get('name')) + ', style = filled') to_print += ('];' + os.linesep) if ((behavior == 'b') or (behavior == 'o') or ((behavior == 'd') and (len(sub) > 1))): if (sub[0].get('color') is not None): to_print += (((('\t\t' + sub_name) + '[label =< <B> ') + sub_name) + '</B>>, style = bold, fillcolor = white, style = filled') else: to_print += (((('\t\t' + sub_name) + '[label = ') + sub_name) + ', style = filled') to_print += ('];' + os.linesep) names_in_this_subgraph = [d.get('name') for d in sub] subgraph_inheritance = [tup for tup in inheritance if ((tup[0] in names_in_this_subgraph) and (tup[1] in names_in_this_subgraph))] subgraph_includes = [tup for tup in includes if ((tup[0] in names_in_this_subgraph) and (tup[1] in names_in_this_subgraph) and (tup not in subgraph_inheritance))] layout = print_subgraph_layout(subgraph_inheritance, subgraph_includes, behavior) to_print += layout to_print += (('\t}//end subgraph ' + sub_name) + os.linesep) dot_file.write(str.encode(to_print)) if (behavior == 'd'): if (len(sub) > 1): subgraph_texts.append(to_print)
def print_subgraph(dot_file, sub_name, sub, behavior='d'): "\n Writes the given subgraph to the given file.\n :param dot_file: The file to write to\n :param sub_name: The subgraph's name\n :param sub: The subgraph to print\n :param behavior: 'd' = dot_file; 'o' = sys_overview; 'b' = block_file\n :return: Nothing\n " to_print = (( + os.linesep) + os.linesep) if (len(sub) is 1): to_print += ((('\tsubgraph ' + sub_name) + ' {') + os.linesep) else: to_print += ((('\tsubgraph cluster' + sub_name) + ' {') + os.linesep) color = sub[0].get('color') subsystem_color_map[sub_name] = color subsystem_color_map_inverse[color] = sub_name if (color is not None): to_print += ('\t\tstyle = rounded' + os.linesep) to_print += (('\t\tbgcolor = ' + lightgray) + os.linesep) to_print += (('\t\tcolor = ' + color) + os.linesep) to_print += (((('\t\tnode [shape = record, color = ' + color) + '];') + os.linesep) + os.linesep) else: to_print += ((('\t\tnode [shape = record];' + os.linesep) + os.linesep) + os.linesep) sub = sorted(sub, key=(lambda nodeInfo: nodeInfo['name'])) for c in sub: to_print += (((('\t\t' + c.get('name')) + '[label = ') + c.get('name')) + ', style = filled') to_print += ('];' + os.linesep) if ((behavior == 'b') or (behavior == 'o') or ((behavior == 'd') and (len(sub) > 1))): if (sub[0].get('color') is not None): to_print += (((('\t\t' + sub_name) + '[label =< <B> ') + sub_name) + '</B>>, style = bold, fillcolor = white, style = filled') else: to_print += (((('\t\t' + sub_name) + '[label = ') + sub_name) + ', style = filled') to_print += ('];' + os.linesep) names_in_this_subgraph = [d.get('name') for d in sub] subgraph_inheritance = [tup for tup in inheritance if ((tup[0] in names_in_this_subgraph) and (tup[1] in names_in_this_subgraph))] subgraph_includes = [tup for tup in includes if ((tup[0] in names_in_this_subgraph) and (tup[1] in names_in_this_subgraph) and (tup not in subgraph_inheritance))] layout = print_subgraph_layout(subgraph_inheritance, subgraph_includes, behavior) to_print += layout to_print += (('\t}//end subgraph ' + sub_name) + os.linesep) dot_file.write(str.encode(to_print)) if (behavior == 'd'): if (len(sub) > 1): subgraph_texts.append(to_print)<|docstring|>Writes the given subgraph to the given file. :param dot_file: The file to write to :param sub_name: The subgraph's name :param sub: The subgraph to print :param behavior: 'd' = dot_file; 'o' = sys_overview; 'b' = block_file :return: Nothing<|endoftext|>
ef0118658cc668b422fe735d95834d2be2e8160d9e7419a5640088c68c22576b
def color_subsystems(subsystems, use_old_discover_mode=False): '\n Colors the subsystems that are bigger than a single item by modifying the "classes" global.\n :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data\n depends on use_old_discover_mode -> if true, this argument should be a list of the form:\n [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc.\n If use_old_discover_mode is false, this argument should be a dictionary of the form:\n {(system_A_\'s_name: [file A, file B, file C]), (system_B_\'s_name: [file_D, file_E]), etc.}\n :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method.\n :return: Nothing\n ' sys_index = 0 iterable = (subsystems if use_old_discover_mode else iter(subsystems.values())) for sys in iterable: if (((len(sys) > 1) and use_old_discover_mode) or ((len(sys) > 0) and (not use_old_discover_mode))): list_of_each_dictionary = [item for item in classes if (item.get('name') in sys)] for dic in list_of_each_dictionary: dic['color'] = SUBSYSTEM_COLORS[sys_index] sys_index = (0 if (sys_index >= (len(SUBSYSTEM_COLORS) - 1)) else (sys_index + 1))
Colors the subsystems that are bigger than a single item by modifying the "classes" global. :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data depends on use_old_discover_mode -> if true, this argument should be a list of the form: [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc. If use_old_discover_mode is false, this argument should be a dictionary of the form: {(system_A_'s_name: [file A, file B, file C]), (system_B_'s_name: [file_D, file_E]), etc.} :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method. :return: Nothing
Tools/DiagramGenerator/dotGenerator.py
color_subsystems
shastrihm/BrainGrid
0
python
def color_subsystems(subsystems, use_old_discover_mode=False): '\n Colors the subsystems that are bigger than a single item by modifying the "classes" global.\n :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data\n depends on use_old_discover_mode -> if true, this argument should be a list of the form:\n [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc.\n If use_old_discover_mode is false, this argument should be a dictionary of the form:\n {(system_A_\'s_name: [file A, file B, file C]), (system_B_\'s_name: [file_D, file_E]), etc.}\n :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method.\n :return: Nothing\n ' sys_index = 0 iterable = (subsystems if use_old_discover_mode else iter(subsystems.values())) for sys in iterable: if (((len(sys) > 1) and use_old_discover_mode) or ((len(sys) > 0) and (not use_old_discover_mode))): list_of_each_dictionary = [item for item in classes if (item.get('name') in sys)] for dic in list_of_each_dictionary: dic['color'] = SUBSYSTEM_COLORS[sys_index] sys_index = (0 if (sys_index >= (len(SUBSYSTEM_COLORS) - 1)) else (sys_index + 1))
def color_subsystems(subsystems, use_old_discover_mode=False): '\n Colors the subsystems that are bigger than a single item by modifying the "classes" global.\n :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data\n depends on use_old_discover_mode -> if true, this argument should be a list of the form:\n [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc.\n If use_old_discover_mode is false, this argument should be a dictionary of the form:\n {(system_A_\'s_name: [file A, file B, file C]), (system_B_\'s_name: [file_D, file_E]), etc.}\n :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method.\n :return: Nothing\n ' sys_index = 0 iterable = (subsystems if use_old_discover_mode else iter(subsystems.values())) for sys in iterable: if (((len(sys) > 1) and use_old_discover_mode) or ((len(sys) > 0) and (not use_old_discover_mode))): list_of_each_dictionary = [item for item in classes if (item.get('name') in sys)] for dic in list_of_each_dictionary: dic['color'] = SUBSYSTEM_COLORS[sys_index] sys_index = (0 if (sys_index >= (len(SUBSYSTEM_COLORS) - 1)) else (sys_index + 1))<|docstring|>Colors the subsystems that are bigger than a single item by modifying the "classes" global. :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data depends on use_old_discover_mode -> if true, this argument should be a list of the form: [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc. If use_old_discover_mode is false, this argument should be a dictionary of the form: {(system_A_'s_name: [file A, file B, file C]), (system_B_'s_name: [file_D, file_E]), etc.} :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method. :return: Nothing<|endoftext|>
9d76fa47de85dffa80dc09630adba385d248a1af04e104f102bffdea93390a1f
def combine_cpp_and_h_files(file_name, map_subsystems_too=False): '\n Finds the .cpp/.cu and .h files that correspond to the given name (name\n is given without a file extension) and combines their contents into a list\n of lines.\n ' lines = [] file_paths = [] for extension in allowable_file_types: if (extension in extension_ignores): continue try: f = find_file((file_name + extension), 'rb') f_lines = [line for line in f] file_paths.append(f.name) f.close() for line in f_lines: lines.append(line) except IOError as ex: pass if (map_subsystems_too and (len(file_paths) > 0)): map_directories(file_paths) return lines
Finds the .cpp/.cu and .h files that correspond to the given name (name is given without a file extension) and combines their contents into a list of lines.
Tools/DiagramGenerator/dotGenerator.py
combine_cpp_and_h_files
shastrihm/BrainGrid
0
python
def combine_cpp_and_h_files(file_name, map_subsystems_too=False): '\n Finds the .cpp/.cu and .h files that correspond to the given name (name\n is given without a file extension) and combines their contents into a list\n of lines.\n ' lines = [] file_paths = [] for extension in allowable_file_types: if (extension in extension_ignores): continue try: f = find_file((file_name + extension), 'rb') f_lines = [line for line in f] file_paths.append(f.name) f.close() for line in f_lines: lines.append(line) except IOError as ex: pass if (map_subsystems_too and (len(file_paths) > 0)): map_directories(file_paths) return lines
def combine_cpp_and_h_files(file_name, map_subsystems_too=False): '\n Finds the .cpp/.cu and .h files that correspond to the given name (name\n is given without a file extension) and combines their contents into a list\n of lines.\n ' lines = [] file_paths = [] for extension in allowable_file_types: if (extension in extension_ignores): continue try: f = find_file((file_name + extension), 'rb') f_lines = [line for line in f] file_paths.append(f.name) f.close() for line in f_lines: lines.append(line) except IOError as ex: pass if (map_subsystems_too and (len(file_paths) > 0)): map_directories(file_paths) return lines<|docstring|>Finds the .cpp/.cu and .h files that correspond to the given name (name is given without a file extension) and combines their contents into a list of lines.<|endoftext|>
7ec0050a2c2e95f9a9ac8b8c1a884d2b423ecee0dc938057bbd83a225bdc2ae3
def crawl_web(center_file_as_list, center_file_name, map_systems_too=False): '\n This function returns a list of lists. Each list being\n all the files that the first item in that list includes, not including .h files (which are\n essentially combined into their like-named .cpp).\n E.g.:\n [ [main, BookStore] , [BookStore, HashTable, Book, Customer, Transaction], [HashTable, etc.], etc. ] <- where main includes BookStore\n and BookStore includes HashTable, Book, Customer, and Transaction, etc.\n ' center_file_name = center_file_name.split(os.sep)[(- 1)].split('.')[0] to_ret = [] stack = [] includes = find_includes(center_file_as_list) if (center_file_name in includes): includes.remove(center_file_name) includes.insert(0, center_file_name) stack.append(includes) while (len(stack) is not 0): el = stack.pop() to_ret.append(el) for e in el: lists_that_e_is_first_item_in = [group for group in to_ret if ((len(group) > 0) and (group[0] == e))] if (len(lists_that_e_is_first_item_in) is 0): e_as_lines = combine_cpp_and_h_files(e, map_systems_too) e_list = find_includes(e_as_lines) if (e in e_list): e_list.remove(e) e_list.insert(0, e) stack.append(e_list) return to_ret
This function returns a list of lists. Each list being all the files that the first item in that list includes, not including .h files (which are essentially combined into their like-named .cpp). E.g.: [ [main, BookStore] , [BookStore, HashTable, Book, Customer, Transaction], [HashTable, etc.], etc. ] <- where main includes BookStore and BookStore includes HashTable, Book, Customer, and Transaction, etc.
Tools/DiagramGenerator/dotGenerator.py
crawl_web
shastrihm/BrainGrid
0
python
def crawl_web(center_file_as_list, center_file_name, map_systems_too=False): '\n This function returns a list of lists. Each list being\n all the files that the first item in that list includes, not including .h files (which are\n essentially combined into their like-named .cpp).\n E.g.:\n [ [main, BookStore] , [BookStore, HashTable, Book, Customer, Transaction], [HashTable, etc.], etc. ] <- where main includes BookStore\n and BookStore includes HashTable, Book, Customer, and Transaction, etc.\n ' center_file_name = center_file_name.split(os.sep)[(- 1)].split('.')[0] to_ret = [] stack = [] includes = find_includes(center_file_as_list) if (center_file_name in includes): includes.remove(center_file_name) includes.insert(0, center_file_name) stack.append(includes) while (len(stack) is not 0): el = stack.pop() to_ret.append(el) for e in el: lists_that_e_is_first_item_in = [group for group in to_ret if ((len(group) > 0) and (group[0] == e))] if (len(lists_that_e_is_first_item_in) is 0): e_as_lines = combine_cpp_and_h_files(e, map_systems_too) e_list = find_includes(e_as_lines) if (e in e_list): e_list.remove(e) e_list.insert(0, e) stack.append(e_list) return to_ret
def crawl_web(center_file_as_list, center_file_name, map_systems_too=False): '\n This function returns a list of lists. Each list being\n all the files that the first item in that list includes, not including .h files (which are\n essentially combined into their like-named .cpp).\n E.g.:\n [ [main, BookStore] , [BookStore, HashTable, Book, Customer, Transaction], [HashTable, etc.], etc. ] <- where main includes BookStore\n and BookStore includes HashTable, Book, Customer, and Transaction, etc.\n ' center_file_name = center_file_name.split(os.sep)[(- 1)].split('.')[0] to_ret = [] stack = [] includes = find_includes(center_file_as_list) if (center_file_name in includes): includes.remove(center_file_name) includes.insert(0, center_file_name) stack.append(includes) while (len(stack) is not 0): el = stack.pop() to_ret.append(el) for e in el: lists_that_e_is_first_item_in = [group for group in to_ret if ((len(group) > 0) and (group[0] == e))] if (len(lists_that_e_is_first_item_in) is 0): e_as_lines = combine_cpp_and_h_files(e, map_systems_too) e_list = find_includes(e_as_lines) if (e in e_list): e_list.remove(e) e_list.insert(0, e) stack.append(e_list) return to_ret<|docstring|>This function returns a list of lists. Each list being all the files that the first item in that list includes, not including .h files (which are essentially combined into their like-named .cpp). E.g.: [ [main, BookStore] , [BookStore, HashTable, Book, Customer, Transaction], [HashTable, etc.], etc. ] <- where main includes BookStore and BookStore includes HashTable, Book, Customer, and Transaction, etc.<|endoftext|>
a47c03d4ec0fcfc7f518fde678ae4c0c8b9e0c4144f9eb9483b22b881d049ab6
def create_subgraphs(subsystems, use_old_discover_mode=False): '\n Changes the layout of the graph to lump all the subsystems together by modifying the "classes" global.\n :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data\n depends on use_old_discover_mode -> if true, this argument should be a list of the form:\n [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc.\n If use_old_discover_mode is false, this argument should be a dictionary of the form:\n {(system_A_\'s_name: [file A, file B, file C]), (system_B_\'s_name: [file_D, file_E]), etc.}\n :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method.\n :return: Nothing\n ' iterable = (subsystems if use_old_discover_mode else iter(subsystems.values())) for (j, sub) in enumerate(iterable): list_of_each_dictionary = [item for item in classes if (item.get('name') in sub)] for dic in list_of_each_dictionary: dic['subgraph'] = j
Changes the layout of the graph to lump all the subsystems together by modifying the "classes" global. :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data depends on use_old_discover_mode -> if true, this argument should be a list of the form: [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc. If use_old_discover_mode is false, this argument should be a dictionary of the form: {(system_A_'s_name: [file A, file B, file C]), (system_B_'s_name: [file_D, file_E]), etc.} :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method. :return: Nothing
Tools/DiagramGenerator/dotGenerator.py
create_subgraphs
shastrihm/BrainGrid
0
python
def create_subgraphs(subsystems, use_old_discover_mode=False): '\n Changes the layout of the graph to lump all the subsystems together by modifying the "classes" global.\n :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data\n depends on use_old_discover_mode -> if true, this argument should be a list of the form:\n [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc.\n If use_old_discover_mode is false, this argument should be a dictionary of the form:\n {(system_A_\'s_name: [file A, file B, file C]), (system_B_\'s_name: [file_D, file_E]), etc.}\n :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method.\n :return: Nothing\n ' iterable = (subsystems if use_old_discover_mode else iter(subsystems.values())) for (j, sub) in enumerate(iterable): list_of_each_dictionary = [item for item in classes if (item.get('name') in sub)] for dic in list_of_each_dictionary: dic['subgraph'] = j
def create_subgraphs(subsystems, use_old_discover_mode=False): '\n Changes the layout of the graph to lump all the subsystems together by modifying the "classes" global.\n :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data\n depends on use_old_discover_mode -> if true, this argument should be a list of the form:\n [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc.\n If use_old_discover_mode is false, this argument should be a dictionary of the form:\n {(system_A_\'s_name: [file A, file B, file C]), (system_B_\'s_name: [file_D, file_E]), etc.}\n :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method.\n :return: Nothing\n ' iterable = (subsystems if use_old_discover_mode else iter(subsystems.values())) for (j, sub) in enumerate(iterable): list_of_each_dictionary = [item for item in classes if (item.get('name') in sub)] for dic in list_of_each_dictionary: dic['subgraph'] = j<|docstring|>Changes the layout of the graph to lump all the subsystems together by modifying the "classes" global. :param subsystems: A list of all the file names lumped into subsystems. The exact nature of this piece of data depends on use_old_discover_mode -> if true, this argument should be a list of the form: [[file_A, file_B, file_C], [file_D, file_E], etc.] where files A through C are one subsystem etc. If use_old_discover_mode is false, this argument should be a dictionary of the form: {(system_A_'s_name: [file A, file B, file C]), (system_B_'s_name: [file_D, file_E]), etc.} :param use_old_discover_mode: Whether or not subsystems was generated using the old-style generation method. :return: Nothing<|endoftext|>
b8e8f895bfadb302622bb3707e84596baef3ff71c39f6b478afc878bdc717d33
def find_file(name, open_mode): "\n Searches from the script's current directory down recursively through all files under it until it finds\n the given file.\n :param name:\n :param open_mode:\n :return:\n " if __file_hash.get(name): return open(__file_hash[name], open_mode) elif (name in iter(__file_hash.values())): return open(name, open_mode) else: raise IOError
Searches from the script's current directory down recursively through all files under it until it finds the given file. :param name: :param open_mode: :return:
Tools/DiagramGenerator/dotGenerator.py
find_file
shastrihm/BrainGrid
0
python
def find_file(name, open_mode): "\n Searches from the script's current directory down recursively through all files under it until it finds\n the given file.\n :param name:\n :param open_mode:\n :return:\n " if __file_hash.get(name): return open(__file_hash[name], open_mode) elif (name in iter(__file_hash.values())): return open(name, open_mode) else: raise IOError
def find_file(name, open_mode): "\n Searches from the script's current directory down recursively through all files under it until it finds\n the given file.\n :param name:\n :param open_mode:\n :return:\n " if __file_hash.get(name): return open(__file_hash[name], open_mode) elif (name in iter(__file_hash.values())): return open(name, open_mode) else: raise IOError<|docstring|>Searches from the script's current directory down recursively through all files under it until it finds the given file. :param name: :param open_mode: :return:<|endoftext|>
2140556b026b23d541c82e0e0aa3fd5ce2e0b2b563517bd1ff4bb7bb3d8f5db0
def form_subsystems_from_inheritance(subsystems): "\n Forms a list of lists ('subsystems') from the input one such that inheritance hierarchies are each a separate\n subsystem.\n :param subsystems:\n :return:\n " for a_inherits_from_b in inheritance: A = a_inherits_from_b[0] B = a_inherits_from_b[1] to_merge = [] for sub in subsystems: if (B in sub): subsystems.remove(sub) to_merge += sub to_merge = list(set(to_merge)) to_merge_including_A = [] for sub in subsystems: if (A in sub): subsystems.remove(sub) to_merge_including_A += sub to_merge += to_merge_including_A to_merge = list(set(to_merge)) subsystems.append(to_merge) return subsystems
Forms a list of lists ('subsystems') from the input one such that inheritance hierarchies are each a separate subsystem. :param subsystems: :return:
Tools/DiagramGenerator/dotGenerator.py
form_subsystems_from_inheritance
shastrihm/BrainGrid
0
python
def form_subsystems_from_inheritance(subsystems): "\n Forms a list of lists ('subsystems') from the input one such that inheritance hierarchies are each a separate\n subsystem.\n :param subsystems:\n :return:\n " for a_inherits_from_b in inheritance: A = a_inherits_from_b[0] B = a_inherits_from_b[1] to_merge = [] for sub in subsystems: if (B in sub): subsystems.remove(sub) to_merge += sub to_merge = list(set(to_merge)) to_merge_including_A = [] for sub in subsystems: if (A in sub): subsystems.remove(sub) to_merge_including_A += sub to_merge += to_merge_including_A to_merge = list(set(to_merge)) subsystems.append(to_merge) return subsystems
def form_subsystems_from_inheritance(subsystems): "\n Forms a list of lists ('subsystems') from the input one such that inheritance hierarchies are each a separate\n subsystem.\n :param subsystems:\n :return:\n " for a_inherits_from_b in inheritance: A = a_inherits_from_b[0] B = a_inherits_from_b[1] to_merge = [] for sub in subsystems: if (B in sub): subsystems.remove(sub) to_merge += sub to_merge = list(set(to_merge)) to_merge_including_A = [] for sub in subsystems: if (A in sub): subsystems.remove(sub) to_merge_including_A += sub to_merge += to_merge_including_A to_merge = list(set(to_merge)) subsystems.append(to_merge) return subsystems<|docstring|>Forms a list of lists ('subsystems') from the input one such that inheritance hierarchies are each a separate subsystem. :param subsystems: :return:<|endoftext|>
164dfa6274b649addfc445d279e9d7396eb1315eef42ef3bc72c58c7a89e771d
def form_subsystems_from_inclusions_in_other_subsystems(subsystems): '\n Check each subsystem A to see if any other subsystem B includes items from A,\n if B includes any items from A and it is the ONLY subsystem that includes any items from A,\n merge A into B.\n E.g. Model, in subsystem B, includes Coordinate, which is its own subsystem A. (Model in B, Coordinate = A).\n B is the ONLY subsystem that includes anything in A, so A should be merged INTO B.\n :param subsystems:\n :return:\n ' for sys_A in subsystems: systems_that_include_from_A = [] for sys_B in subsystems: if (sys_B == sys_A): continue elif list_includes_any_items_from_other_list(sys_B, sys_A): systems_that_include_from_A.append(sys_B) for potential_subset in systems_that_include_from_A: for other in systems_that_include_from_A: if (potential_subset == other): continue elif (set(potential_subset).issubset(set(other)) and (potential_subset in systems_that_include_from_A)): systems_that_include_from_A.remove(potential_subset) if ((len(systems_that_include_from_A) is 1) and (len(systems_that_include_from_A[0]) is not 1)): subsystems.remove(sys_A) subsystems.append(list(set((sys_A + systems_that_include_from_A[0])))) return subsystems
Check each subsystem A to see if any other subsystem B includes items from A, if B includes any items from A and it is the ONLY subsystem that includes any items from A, merge A into B. E.g. Model, in subsystem B, includes Coordinate, which is its own subsystem A. (Model in B, Coordinate = A). B is the ONLY subsystem that includes anything in A, so A should be merged INTO B. :param subsystems: :return:
Tools/DiagramGenerator/dotGenerator.py
form_subsystems_from_inclusions_in_other_subsystems
shastrihm/BrainGrid
0
python
def form_subsystems_from_inclusions_in_other_subsystems(subsystems): '\n Check each subsystem A to see if any other subsystem B includes items from A,\n if B includes any items from A and it is the ONLY subsystem that includes any items from A,\n merge A into B.\n E.g. Model, in subsystem B, includes Coordinate, which is its own subsystem A. (Model in B, Coordinate = A).\n B is the ONLY subsystem that includes anything in A, so A should be merged INTO B.\n :param subsystems:\n :return:\n ' for sys_A in subsystems: systems_that_include_from_A = [] for sys_B in subsystems: if (sys_B == sys_A): continue elif list_includes_any_items_from_other_list(sys_B, sys_A): systems_that_include_from_A.append(sys_B) for potential_subset in systems_that_include_from_A: for other in systems_that_include_from_A: if (potential_subset == other): continue elif (set(potential_subset).issubset(set(other)) and (potential_subset in systems_that_include_from_A)): systems_that_include_from_A.remove(potential_subset) if ((len(systems_that_include_from_A) is 1) and (len(systems_that_include_from_A[0]) is not 1)): subsystems.remove(sys_A) subsystems.append(list(set((sys_A + systems_that_include_from_A[0])))) return subsystems
def form_subsystems_from_inclusions_in_other_subsystems(subsystems): '\n Check each subsystem A to see if any other subsystem B includes items from A,\n if B includes any items from A and it is the ONLY subsystem that includes any items from A,\n merge A into B.\n E.g. Model, in subsystem B, includes Coordinate, which is its own subsystem A. (Model in B, Coordinate = A).\n B is the ONLY subsystem that includes anything in A, so A should be merged INTO B.\n :param subsystems:\n :return:\n ' for sys_A in subsystems: systems_that_include_from_A = [] for sys_B in subsystems: if (sys_B == sys_A): continue elif list_includes_any_items_from_other_list(sys_B, sys_A): systems_that_include_from_A.append(sys_B) for potential_subset in systems_that_include_from_A: for other in systems_that_include_from_A: if (potential_subset == other): continue elif (set(potential_subset).issubset(set(other)) and (potential_subset in systems_that_include_from_A)): systems_that_include_from_A.remove(potential_subset) if ((len(systems_that_include_from_A) is 1) and (len(systems_that_include_from_A[0]) is not 1)): subsystems.remove(sys_A) subsystems.append(list(set((sys_A + systems_that_include_from_A[0])))) return subsystems<|docstring|>Check each subsystem A to see if any other subsystem B includes items from A, if B includes any items from A and it is the ONLY subsystem that includes any items from A, merge A into B. E.g. Model, in subsystem B, includes Coordinate, which is its own subsystem A. (Model in B, Coordinate = A). B is the ONLY subsystem that includes anything in A, so A should be merged INTO B. :param subsystems: :return:<|endoftext|>