uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
552d9a178a1a6497c1792917 | train | function | def mse_loss_with_nans(input, target):
# Missing data are nan's
mask = torch.isnan(target)
out = (input[~mask]-target[~mask])**2
loss = out.mean()
return loss
| def mse_loss_with_nans(input, target):
# Missing data are nan's
| mask = torch.isnan(target)
out = (input[~mask]-target[~mask])**2
loss = out.mean()
return loss
| email__ = "damien.x.coupry@gsk.com"
__status__ = "Dev"
NODE_FEATURES = 39
EDGE_FEATURES = 10
pytorch_lightning.seed_everything(42)
def mse_loss_with_nans(input, target):
# Missing data are nan's
| 64 | 64 | 52 | 18 | 46 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | mse_loss_with_nans | mse_loss_with_nans | 28 | 33 | 28 | 29 | ac26504cb0366ea91ad1b7b1bb37ae9139cdaf18 | bigcode/the-stack | train |
d11b4bbc8513c36d5a89f780 | train | class | class DenseGraphNetwork(torch.nn.Module):
def __init__(self,
hidden_size: int,
output_size: int = 1,
graph_depth: int = 3,
fc_depth: int = 3,
dropout: float = 0.1,
extra_features: Optional[List[torch.nn.Module]] = ... | class DenseGraphNetwork(torch.nn.Module):
| def __init__(self,
hidden_size: int,
output_size: int = 1,
graph_depth: int = 3,
fc_depth: int = 3,
dropout: float = 0.1,
extra_features: Optional[List[torch.nn.Module]] = None,
) -> None:
... | _heads),
torch.nn.PReLU(hidden_size * num_heads))
self.pool_edge = torch.nn.Sequential(torch.nn.Linear(graph_dims[-1][1] + hidden_size, hidden_size),
torch.nn.PReLU(hidden_size))
self.attend_node = GraphAttentionLa... | 215 | 215 | 719 | 8 | 206 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | DenseGraphNetwork | DenseGraphNetwork | 196 | 300 | 196 | 196 | 20f8adfab5f9b3b2ca825553400c9e1e69eb4652 | bigcode/the-stack | train |
0e0b716fb7b42c147158f9f4 | train | class | class GraphNetwork(torch.nn.Module):
def __init__(self,
hidden_size: int,
output_size: int = 1,
graph_depth: int = 3,
fc_depth: int = 3,
dropout: float = 0.1,
extra_features: Optional[List[torch.nn.Module]] = None,... | class GraphNetwork(torch.nn.Module):
| def __init__(self,
hidden_size: int,
output_size: int = 1,
graph_depth: int = 3,
fc_depth: int = 3,
dropout: float = 0.1,
extra_features: Optional[List[torch.nn.Module]] = None,
) -> None:
... | x
u = torch.zeros(batch.max()+1, n.size(1), dtype=n.dtype, device=n.device)
u = u.index_add_(0, batch, n)
densify_u = [u, ]
for gl in self.graph_layers:
n, e, u = gl(n, e, e_i, batch)
Us.append(u)
u = torch.cat(Us, dim=-1)
u = self.fc_layers(u)
... | 207 | 207 | 690 | 7 | 199 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | GraphNetwork | GraphNetwork | 302 | 403 | 302 | 302 | f9fa6fd53f16c61580b7cad30188099b5fcbd09f | bigcode/the-stack | train |
84a332b3e13aff3ce3ca141e | train | class | class GraphNetworkLigthning(pytorch_lightning.LightningModule):
"""
"""
def __init__(self,
hparams: argparse.Namespace,
) -> None:
"""
[summary]
Parameters
----------
hparams : argparse.Namespace
[description]
Re... | class GraphNetworkLigthning(pytorch_lightning.LightningModule):
| """
"""
def __init__(self,
hparams: argparse.Namespace,
) -> None:
"""
[summary]
Parameters
----------
hparams : argparse.Namespace
[description]
Returns
-------
[type]
[description]
... | [description]
"""
n, e, e_i, batch = x
for gl in self.graph_layers:
n, e = gl(n, e_i, e)
u = torch.zeros(batch.max()+1, n.size(1), dtype=n.dtype, device=n.device)
u = u.index_add_(0, batch, n)
u = self.fc_layers(u)
return u
def... | 201 | 201 | 673 | 14 | 186 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | GraphNetworkLigthning | GraphNetworkLigthning | 406 | 528 | 406 | 406 | 60ee9e82eb0241b31df8f1d9c3f4a19834f91d09 | bigcode/the-stack | train |
081334195d8b2e9e39e3cf3c | train | class | class GraphNetworkEnsembleLightning(pytorch_lightning.LightningModule):
"""
"""
def __init__(self,
models: List[torch.nn.Module],
loss: torch.nn.Module,
prediction_names: List[str]
) -> None:
"""
[summary]
Par... | class GraphNetworkEnsembleLightning(pytorch_lightning.LightningModule):
| """
"""
def __init__(self,
models: List[torch.nn.Module],
loss: torch.nn.Module,
prediction_names: List[str]
) -> None:
"""
[summary]
Parameters
----------
models : List[torch.nn.Module]
... | have not the same output dim
Returns
-------
Tuple[torch.Tensor, torch.Tensor]
[description]
"""
# first enable dropout
for m in self.modules():
if m.__class__.__name__.startswith("Dropout"):
m.train()
outs = []
... | 142 | 142 | 476 | 14 | 127 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | GraphNetworkEnsembleLightning | GraphNetworkEnsembleLightning | 624 | 719 | 624 | 624 | f5d53d581d791c76c3dc0bb53d7d96c0146deee8 | bigcode/the-stack | train |
1b233844a7c1d679f8076bee | train | class | class DenseGraphBlock(torch.nn.Module):
def __init__(self,
node_features_size: int,
edge_features_size: int,
hidden_size: int,
num_heads: int = 4,
depth: int = 3) -> None:
super().__init__()
node_dims = [node_feat... | class DenseGraphBlock(torch.nn.Module):
| def __init__(self,
node_features_size: int,
edge_features_size: int,
hidden_size: int,
num_heads: int = 4,
depth: int = 3) -> None:
super().__init__()
node_dims = [node_features_size, ] + [hidden_size for _ in ran... | ([node_features[senders],
edge_features], dim=-1))
updated_edge_features = self.dropedges(updated_edge_features.unsqueeze(0)).squeeze(0)
node_features_update = torch.zeros(node_features.size(0),
updated... | 128 | 128 | 429 | 8 | 119 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | DenseGraphBlock | DenseGraphBlock | 153 | 194 | 153 | 153 | 2eeedf591e98b431126f482d2dfcf1bfe60268ad | bigcode/the-stack | train |
90a40779ed7ad6f62484fee1 | train | class | class ExplainerNetworkLightning(pytorch_lightning.LightningModule):
"""
"""
def __init__(self, task : str = "regression", property_index : int = 0) -> None:
"""
[summary]
Parameters
----------
task : str, optional
[description], by default "regression"
... | class ExplainerNetworkLightning(pytorch_lightning.LightningModule):
| """
"""
def __init__(self, task : str = "regression", property_index : int = 0) -> None:
"""
[summary]
Parameters
----------
task : str, optional
[description], by default "regression"
Returns
-------
[type]
[descripti... | torch.nn.Tanh())
self.node_model = torch.nn.Sequential(torch.nn.Linear(NODE_INPUT_SIZE, HIDDEN_SIZE),
torch.nn.Tanh(),
torch.nn.Linear(HIDDEN_SIZE, 1))
return None
... | 209 | 209 | 699 | 13 | 195 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | ExplainerNetworkLightning | ExplainerNetworkLightning | 755 | 875 | 755 | 755 | 064c6b06541b5fcf97867d96fbe71ad7b42ebb1d | bigcode/the-stack | train |
1c3dfe4259edbd9ad5d45132 | train | class | class GraphAttentionLayer(torch.nn.Module):
def __init__(self,
hidden_size: int,
num_heads: int) -> None:
"""
[summary]
Parameters
----------
hidden_size : int
[description]
depth : int
[description]
... | class GraphAttentionLayer(torch.nn.Module):
| def __init__(self,
hidden_size: int,
num_heads: int) -> None:
"""
[summary]
Parameters
----------
hidden_size : int
[description]
depth : int
[description]
dropout : float
[description]
... | "
NODE_FEATURES = 39
EDGE_FEATURES = 10
pytorch_lightning.seed_everything(42)
def mse_loss_with_nans(input, target):
# Missing data are nan's
mask = torch.isnan(target)
out = (input[~mask]-target[~mask])**2
loss = out.mean()
return loss
class GraphAttentionLayer(torch.nn.Module):
| 85 | 85 | 284 | 8 | 76 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | GraphAttentionLayer | GraphAttentionLayer | 36 | 81 | 36 | 36 | d31fd72ccb9d971a29c574e7b7c118b0eb83ff49 | bigcode/the-stack | train |
5e1d9860a02fd00b87f26c7d | train | class | class GraphNetworkEnsemble(torch.nn.Module):
"""
"""
def __init__(self,
models: List[torch.nn.Module],
prediction_names: List[str]) -> None:
"""
[summary]
Parameters
----------
models : List[torch.nn.Module]
[descrip... | class GraphNetworkEnsemble(torch.nn.Module):
| """
"""
def __init__(self,
models: List[torch.nn.Module],
prediction_names: List[str]) -> None:
"""
[summary]
Parameters
----------
models : List[torch.nn.Module]
[description]
"""
super().__i... | .parameters(),
# lr=self.hparams.learning_rate,
# weight_decay=self.hparams.weight_decay,
# betas=(self.hparams.beta1, self.hparams.beta2))
# scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer,
# ... | 131 | 132 | 440 | 9 | 122 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | GraphNetworkEnsemble | GraphNetworkEnsemble | 543 | 621 | 543 | 543 | 51d3421af68854e0c688426159def85765bbae03 | bigcode/the-stack | train |
e48d594285e824f41d4d6cee | train | class | class GraphLayer(torch.nn.Module):
"""
"""
def __init__(self,
node_features_size: int,
edge_features_size: int,
hidden_size: int,
) -> None:
"""
[summary]
Parameters
----------
node_features_size : ... | class GraphLayer(torch.nn.Module):
| """
"""
def __init__(self,
node_features_size: int,
edge_features_size: int,
hidden_size: int,
) -> None:
"""
[summary]
Parameters
----------
node_features_size : int
[description]
... | _indices : torch.Tensor
[description]
Returns
-------
torch.Tensor
[description]
"""
_, seq_lengths = torch.unique(batch_indices, sorted=False, return_counts=True)
sequences = torch.split(node_features, seq_lengths.tolist())
src = torch.nn... | 139 | 139 | 465 | 7 | 132 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | GraphLayer | GraphLayer | 83 | 151 | 83 | 83 | 2582812c17466883c28f4be4ff04f5fcab43f550 | bigcode/the-stack | train |
789119493c1e3f307e96a628 | train | class | class ExplainerNetwork(torch.nn.Module):
def __init__(self) -> None:
"""
"""
super().__init__()
HIDDEN_SIZE = 32
EDGE_INPUT_SIZE = EDGE_FEATURES + 2 * NODE_FEATURES
NODE_INPUT_SIZE = HIDDEN_SIZE + NODE_FEATURES
self.edge_model = torch.nn.Sequential(torch.nn.Li... | class ExplainerNetwork(torch.nn.Module):
| def __init__(self) -> None:
"""
"""
super().__init__()
HIDDEN_SIZE = 32
EDGE_INPUT_SIZE = EDGE_FEATURES + 2 * NODE_FEATURES
NODE_INPUT_SIZE = HIDDEN_SIZE + NODE_FEATURES
self.edge_model = torch.nn.Sequential(torch.nn.Linear(EDGE_INPUT_SIZE, HIDDEN_SIZE),
... | [description]
Returns
-------
float
[description]
"""
x, y = batch
yhats = self.forward(x)
loss = self._loss(yhats, y)
self.log('test_loss', loss)
return loss
def configure_optimizers(self) -> None:
"""
[s... | 89 | 89 | 298 | 8 | 80 | DCoupry/MPNNQSAR | dmpnn/models.py | Python | ExplainerNetwork | ExplainerNetwork | 722 | 752 | 722 | 722 | fb77287318351be884bbf5735ebac1b79c8ad133 | bigcode/the-stack | train |
08439d0e74234095774ba2f2 | train | function | def display(order, start):
""" Convert to readable format.
"""
res = []
c = start
while len(res) < len(order)-1:
res.append(str(c))
c = order[c]
return " ".join(res)
| def display(order, start):
| """ Convert to readable format.
"""
res = []
c = start
while len(res) < len(order)-1:
res.append(str(c))
c = order[c]
return " ".join(res)
| import csv
import time
import copy
import numpy as np
def display(order, start):
| 20 | 64 | 54 | 6 | 13 | danielmohansahu/advent_of_code | 2020/23/soln2.py | Python | display | display | 6 | 14 | 6 | 6 | 42fb2ec6608562dda31267bbee31b3ceea5e95c9 | bigcode/the-stack | train |
77d2c8ae5b3309fc6d66c25d | train | function | def move(order, current):
""" Perform a move on the given list.
Returns the new current cup.
"""
# get next three cups
popped = [order[current]]
for i in range(2):
popped.append(order[popped[-1]])
# find destination
dest = current
while True:
dest = (dest-1) if (... | def move(order, current):
| """ Perform a move on the given list.
Returns the new current cup.
"""
# get next three cups
popped = [order[current]]
for i in range(2):
popped.append(order[popped[-1]])
# find destination
dest = current
while True:
dest = (dest-1) if (dest-1 != 0) else len(orde... | numpy as np
def display(order, start):
""" Convert to readable format.
"""
res = []
c = start
while len(res) < len(order)-1:
res.append(str(c))
c = order[c]
return " ".join(res)
def move(order, current):
| 64 | 64 | 201 | 6 | 58 | danielmohansahu/advent_of_code | 2020/23/soln2.py | Python | move | move | 16 | 45 | 16 | 16 | 708ff53054a765c891b59fa6db4e173c827be2fb | bigcode/the-stack | train |
8206b32eed67ee7c6ac0eea3 | train | class | class UidValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="uid", parent_name="scattergeo", **kwargs):
super(UidValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
... | class UidValidator(_plotly_utils.basevalidators.StringValidator):
| def __init__(self, plotly_name="uid", parent_name="scattergeo", **kwargs):
super(UidValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
**kwargs,
)
| import _plotly_utils.basevalidators
class UidValidator(_plotly_utils.basevalidators.StringValidator):
| 21 | 64 | 80 | 13 | 7 | mastermind88/plotly.py | packages/python/plotly/plotly/validators/scattergeo/_uid.py | Python | UidValidator | UidValidator | 4 | 11 | 4 | 4 | 9dd68aa39f7ad611e3d059ada357fd1b78afaea2 | bigcode/the-stack | train |
426469f65830bef8e5ff66d6 | train | function | def define_default_flags(flags):
"""Default flags for a view synthesis trainer.
Args:
flags: loaded flags module
"""
## Flags for logging and snapshotting
flags.DEFINE_string('checkpoint_dir',
'/code/lsi/cachedir/snapshots/',
'Root directory for tensorflow out... | def define_default_flags(flags):
| """Default flags for a view synthesis trainer.
Args:
flags: loaded flags module
"""
## Flags for logging and snapshotting
flags.DEFINE_string('checkpoint_dir',
'/code/lsi/cachedir/snapshots/',
'Root directory for tensorflow output files.')
flags.DEFINE_strin... | import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import logging as log
from lsi.nnutils import helpers as nn_helpers
from lsi.visualization import html_utils
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import scipy.misc
imp... | 89 | 89 | 298 | 6 | 82 | google/layered-scene-inference | lsi/nnutils/test_utils.py | Python | define_default_flags | define_default_flags | 36 | 66 | 36 | 36 | 03066d21532bfd1d9b340d313b60011e06cde5b8 | bigcode/the-stack | train |
41e6ba38ae6081b3346f53a3 | train | class | class Tester(object):
"""Generic class for a view synthesis tester.
"""
def __init__(self, opts):
self.opts = opts
def define_data_loader(self):
"""Should be implemented by the child class."""
raise NotImplementedError
def define_placeholders(self):
"""Define placeholders.
"""
opts ... | class Tester(object):
| """Generic class for a view synthesis tester.
"""
def __init__(self, opts):
self.opts = opts
def define_data_loader(self):
"""Should be implemented by the child class."""
raise NotImplementedError
def define_placeholders(self):
"""Define placeholders.
"""
opts = self.opts
img_he... | '/code/lsi/cachedir/snapshots/',
'Root directory for tensorflow output files.')
flags.DEFINE_string('results_vis_dir',
'/code/lsi/cachedir/visualization/',
'Root directory for image output files.')
flags.DEFINE_string('results_eval_dir',
... | 255 | 256 | 1,403 | 4 | 251 | google/layered-scene-inference | lsi/nnutils/test_utils.py | Python | Tester | Tester | 69 | 255 | 69 | 69 | f9f915787da52d203c77c11912bd396881f1206e | bigcode/the-stack | train |
f5427c51a7610b8fae84b361 | train | class | class AnalyzeHealthcareEntitiesLROPoller(LROPoller, Generic[PollingReturnType]):
def polling_method(self):
# type: () -> AnalyzeHealthcareEntitiesLROPollingMethod
"""Return the polling method associated to this poller."""
return self._polling_method # type: ignore
@property
def cre... | class AnalyzeHealthcareEntitiesLROPoller(LROPoller, Generic[PollingReturnType]):
| def polling_method(self):
# type: () -> AnalyzeHealthcareEntitiesLROPollingMethod
"""Return the polling method associated to this poller."""
return self._polling_method # type: ignore
@property
def created_on(self):
# type: () -> datetime.datetime
"""When your healt... | (AnalyzeHealthcareEntitiesLROPollingMethod, self).__init__(*args, **kwargs)
@property
def _current_body(self):
from ._generated.models import JobMetadata
return JobMetadata.deserialize(self._pipeline_response)
@property
def created_on(self):
if not self._current_body:
... | 196 | 196 | 655 | 17 | 178 | rsdoherty/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py | Python | AnalyzeHealthcareEntitiesLROPoller | AnalyzeHealthcareEntitiesLROPoller | 147 | 230 | 147 | 147 | 2ad5db7139c894371be0568742db1f10a7991c47 | bigcode/the-stack | train |
374efec166c4606416a5e124 | train | class | class AnalyzeActionsLROPoller(LROPoller, Generic[PollingReturnType]):
def polling_method(self):
# type: () -> AnalyzeActionsLROPollingMethod
"""Return the polling method associated to this poller."""
return self._polling_method # type: ignore
@property
def created_on(self):
... | class AnalyzeActionsLROPoller(LROPoller, Generic[PollingReturnType]):
| def polling_method(self):
# type: () -> AnalyzeActionsLROPollingMethod
"""Return the polling method associated to this poller."""
return self._polling_method # type: ignore
@property
def created_on(self):
# type: () -> datetime.datetime
"""When your analyze job was ... | "]["failed"]
@property
def actions_in_progress_count(self):
if not self._current_body:
return None
return self._current_body.additional_properties["tasks"]["inProgress"]
@property
def actions_succeeded_count(self):
if not self._current_body:
return None
... | 194 | 194 | 649 | 16 | 177 | rsdoherty/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py | Python | AnalyzeActionsLROPoller | AnalyzeActionsLROPoller | 295 | 392 | 295 | 295 | 2250603e864b55bdf3ce8f9910398573d9654599 | bigcode/the-stack | train |
87228deebe241a9c9b44bf5e | train | class | class TextAnalyticsOperationResourcePolling(OperationResourcePolling):
def __init__(
self, operation_location_header="operation-location", show_stats=False
):
super(TextAnalyticsOperationResourcePolling, self).__init__(
operation_location_header=operation_location_header
)
... | class TextAnalyticsOperationResourcePolling(OperationResourcePolling):
| def __init__(
self, operation_location_header="operation-location", show_stats=False
):
super(TextAnalyticsOperationResourcePolling, self).__init__(
operation_location_header=operation_location_header
)
self._show_stats = show_stats
self._query_params = {"show... | ucceeded", "cancelled", "failed", "partiallycompleted"])
_FAILED = frozenset(["failed"])
_SUCCEEDED = frozenset(["succeeded", "partiallycompleted"])
if TYPE_CHECKING:
from typing import Any, Optional
import datetime
class TextAnalyticsOperationResourcePolling(OperationResourcePolling):
| 64 | 64 | 140 | 10 | 53 | rsdoherty/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py | Python | TextAnalyticsOperationResourcePolling | TextAnalyticsOperationResourcePolling | 27 | 45 | 27 | 27 | 1620c70704b41be8bba52caaf233e71b64035759 | bigcode/the-stack | train |
d1a719c44671355588cecc12 | train | class | class AnalyzeHealthcareEntitiesLROPollingMethod(TextAnalyticsLROPollingMethod):
def __init__(self, *args, **kwargs):
self._text_analytics_client = kwargs.pop("text_analytics_client")
super(AnalyzeHealthcareEntitiesLROPollingMethod, self).__init__(*args, **kwargs)
@property
def _current_body... | class AnalyzeHealthcareEntitiesLROPollingMethod(TextAnalyticsLROPollingMethod):
| def __init__(self, *args, **kwargs):
self._text_analytics_client = kwargs.pop("text_analytics_client")
super(AnalyzeHealthcareEntitiesLROPollingMethod, self).__init__(*args, **kwargs)
@property
def _current_body(self):
from ._generated.models import JobMetadata
return JobMe... | (self._pipeline_response)
if final_get_url:
self._pipeline_response = self.request_status(final_get_url)
TextAnalyticsLROPollingMethod._raise_if_bad_http_status_and_method(
self._pipeline_response.http_response
)
class AnalyzeHealthcareEntitiesLROPollingMethod... | 68 | 68 | 227 | 17 | 51 | rsdoherty/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py | Python | AnalyzeHealthcareEntitiesLROPollingMethod | AnalyzeHealthcareEntitiesLROPollingMethod | 111 | 144 | 111 | 111 | b383184b7daeab026b3aef00a115593faa3e6f26 | bigcode/the-stack | train |
2bd126be2782d2868c1f51f8 | train | class | class AnalyzeActionsLROPollingMethod(TextAnalyticsLROPollingMethod):
@property
def _current_body(self):
from ._generated.models import AnalyzeJobMetadata
return AnalyzeJobMetadata.deserialize(self._pipeline_response)
@property
def created_on(self):
if not self._current_body:
... | class AnalyzeActionsLROPollingMethod(TextAnalyticsLROPollingMethod):
@property
| def _current_body(self):
from ._generated.models import AnalyzeJobMetadata
return AnalyzeJobMetadata.deserialize(self._pipeline_response)
@property
def created_on(self):
if not self._current_body:
return None
return self._current_body.created_date_time
@pro... | .
getattr(self._polling_method, "update_status")()
return getattr(
self._polling_method, "_text_analytics_client"
).begin_cancel_health_job(
self.id, polling=TextAnalyticsLROPollingMethod(timeout=polling_interval)
)
except HttpRes... | 106 | 106 | 356 | 20 | 86 | rsdoherty/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py | Python | AnalyzeActionsLROPollingMethod | AnalyzeActionsLROPollingMethod | 233 | 292 | 233 | 234 | c2db72348aaaf599e2df4cc284f4b02066099c44 | bigcode/the-stack | train |
c67d5801161b3c7d49c342d5 | train | class | class TextAnalyticsLROPollingMethod(LROBasePolling):
def finished(self):
"""Is this polling finished?
:rtype: bool
"""
return TextAnalyticsLROPollingMethod._finished(self.status())
@staticmethod
def _finished(status):
if hasattr(status, "value"):
status ... | class TextAnalyticsLROPollingMethod(LROBasePolling):
| def finished(self):
"""Is this polling finished?
:rtype: bool
"""
return TextAnalyticsLROPollingMethod._finished(self.status())
@staticmethod
def _finished(status):
if hasattr(status, "value"):
status = status.value
return str(status).lower() in ... | _stats=False
):
super(TextAnalyticsOperationResourcePolling, self).__init__(
operation_location_header=operation_location_header
)
self._show_stats = show_stats
self._query_params = {"showStats": show_stats}
def get_polling_url(self):
if not self._show_stats:... | 127 | 127 | 424 | 13 | 114 | rsdoherty/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py | Python | TextAnalyticsLROPollingMethod | TextAnalyticsLROPollingMethod | 48 | 108 | 48 | 48 | 5e9d8dc4bd9a93d0e44ab4fa7ae4afdfdc586271 | bigcode/the-stack | train |
e02ef21d1455a76319835d6a | train | function | @app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for user {}, host {}, db {}, remember_me={}'.format(
form.username.data, form.host.data, form.db.data, form.remember_me.data))
conn = connect_db(form.hos... | @app.route('/login', methods=['GET', 'POST'])
def login():
| form = LoginForm()
if form.validate_on_submit():
flash('Login requested for user {}, host {}, db {}, remember_me={}'.format(
form.username.data, form.host.data, form.db.data, form.remember_me.data))
conn = connect_db(form.host.data, form.db.data, form.username.data, form.password.dat... | },
{
'author': {'username': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
return render_template('index.html', title='Home', user=user, posts=posts)
@app.route('/login', methods=['GET', 'POST'])
def login():
| 64 | 64 | 111 | 15 | 49 | sqoor/SeqGenSQL-ui | app/routes.py | Python | login | login | 23 | 32 | 23 | 24 | f49d39e8076455823ebea5cdae8e8db722363a87 | bigcode/the-stack | train |
5e296a60bd96697978cb87a3 | train | function | @app.route('/', methods=['GET', 'POST'])
@app.route('/connect', methods=['GET', 'POST'])
def connect():
form = ConnectForm()
if form.validate_on_submit():
conn = connect_db(form.server.data, form.db.data, form.username.data, form.password.data)
if conn.error:
flash('Connection Error ... | @app.route('/', methods=['GET', 'POST'])
@app.route('/connect', methods=['GET', 'POST'])
def connect():
| form = ConnectForm()
if form.validate_on_submit():
conn = connect_db(form.server.data, form.db.data, form.username.data, form.password.data)
if conn.error:
flash('Connection Error {}'.format(conn.error))
render_template('connect-form.html', title='Connect to The Database'... | .data, form.db.data, form.username.data, form.password.data)
return redirect(url_for('convert'))
return render_template('login.html', title='Sign In', form=form)
@app.route('/', methods=['GET', 'POST'])
@app.route('/connect', methods=['GET', 'POST'])
def connect():
| 64 | 64 | 137 | 25 | 39 | sqoor/SeqGenSQL-ui | app/routes.py | Python | connect | connect | 35 | 47 | 35 | 37 | 86074c3ba85f243bf1fb1766c94d97f097f26fd9 | bigcode/the-stack | train |
04ebe1ba0b51bda7622ab9cc | train | function | @app.route('/table', methods=['GET', 'POST'])
def table():
return render_template('table.html', title='Enter the text to convert into SQL', data={})
| @app.route('/table', methods=['GET', 'POST'])
def table():
| return render_template('table.html', title='Enter the text to convert into SQL', data={})
| render_template('table2.html', title='Enter the text to convert into SQL', rows=rows, columns=columns)
return render_template('convert-form.html', title='Enter the text to convert into SQL', form=form)
@app.route('/table', methods=['GET', 'POST'])
def table():
| 64 | 64 | 37 | 15 | 49 | sqoor/SeqGenSQL-ui | app/routes.py | Python | table | table | 74 | 76 | 74 | 75 | 095eb4c9f3000d4877f21d0f9b0689a417ff533c | bigcode/the-stack | train |
41054e0ac3ea2dd9bf108020 | train | function | @app.route('/convert', methods=['GET', 'POST'])
def convert():
form = ConvertForm()
if form.validate_on_submit():
conn = get_db()
result = conn.run_via_cursor(form.text.data)
if isinstance(result, str):
# error happend executing sql query
flash('Convert F... | @app.route('/convert', methods=['GET', 'POST'])
def convert():
| form = ConvertForm()
if form.validate_on_submit():
conn = get_db()
result = conn.run_via_cursor(form.text.data)
if isinstance(result, str):
# error happend executing sql query
flash('Convert From requested text {}'.format(result))
return rende... | ', connError="hi-error", form=form)
else:
flash('Connected successfully to the database')
return redirect(url_for('convert'))
return render_template('connect-form.html', title='Connect to The Database', form=form)
@app.route('/convert', methods=['GET', 'POST'])
def convert():
| 64 | 64 | 192 | 15 | 49 | sqoor/SeqGenSQL-ui | app/routes.py | Python | convert | convert | 50 | 70 | 50 | 51 | 45a7e2f39211643c2378e6936597928cb21d38d6 | bigcode/the-stack | train |
cb2a6626568b742dc8243d29 | train | function | @app.route('/index')
def index():
user = {'username': 'Miguel'}
posts = [
{
'author': {'username': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'username': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]... | @app.route('/index')
def index():
| user = {'username': 'Miguel'}
posts = [
{
'author': {'username': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'username': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
return render_template('index... | from flask import render_template, flash, redirect, url_for, session
from app import app
from app.forms import LoginForm, ConnectForm, ConvertForm
from db import Connection, get_db, close_db, connect_db
@app.route('/index')
def index():
| 55 | 64 | 93 | 8 | 46 | sqoor/SeqGenSQL-ui | app/routes.py | Python | index | index | 7 | 20 | 7 | 8 | c4af4d7130ccd7e4476896df143719dafa3614a7 | bigcode/the-stack | train |
aed19c9d5a33ea8b257c13ad | train | function | def namedtuple(typename, field_names, defaults=None):
if not defaults:
# No defaults given or needed
return _namedtuple(typename, field_names)
try:
# Python 3.7+
return _namedtuple(typename, field_names, defaults=defaults)
except TypeError:
T = _namedtuple(typename, f... | def namedtuple(typename, field_names, defaults=None):
| if not defaults:
# No defaults given or needed
return _namedtuple(typename, field_names)
try:
# Python 3.7+
return _namedtuple(typename, field_names, defaults=defaults)
except TypeError:
T = _namedtuple(typename, field_names)
# Python 2.7, up to 3.6
T.... | from collections import namedtuple as _namedtuple
# version-portable namedtuple with defaults
def namedtuple(typename, field_names, defaults=None):
| 31 | 64 | 108 | 12 | 18 | dieter-exc/python-pcapng | pcapng/_compat.py | Python | namedtuple | namedtuple | 5 | 16 | 5 | 5 | 3f83fd39e79a040cf0461c747ae70ef45b0719a9 | bigcode/the-stack | train |
cf20d5d25909fce3b814174b | train | class | class NamedModel(models.Model):
name = models.CharField(max_length=25)
class Meta:
abstract = True
def __str__(self):
return self.name
| class NamedModel(models.Model):
| name = models.CharField(max_length=25)
class Meta:
abstract = True
def __str__(self):
return self.name
| from django.contrib.gis.db import models
class NamedModel(models.Model):
| 15 | 64 | 38 | 6 | 8 | txf626/django | tests/gis_tests/layermap/models.py | Python | NamedModel | NamedModel | 4 | 11 | 4 | 4 | ac892ccf2af09683985bef307ae3e002abd7e137 | bigcode/the-stack | train |
39ecb0ced2cbee1c81e5e602 | train | class | class ICity2(ICity1):
dt_time = models.DateTimeField(auto_now=True)
class Meta(ICity1.Meta):
pass
| class ICity2(ICity1):
| dt_time = models.DateTimeField(auto_now=True)
class Meta(ICity1.Meta):
pass
| population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
point = models.PointField()
class ICity1(CityBase):
dt = models.DateField()
class Meta(CityBase.Meta):
pass
class ICity2(ICity1):
| 64 | 64 | 31 | 8 | 55 | txf626/django | tests/gis_tests/layermap/models.py | Python | ICity2 | ICity2 | 61 | 65 | 61 | 61 | d96433128ff93d8bd6f47d6423a1bff145ef7ddc | bigcode/the-stack | train |
11a739530feda64ff6a30128 | train | class | class County(NamedModel):
state = models.ForeignKey(State, models.CASCADE)
mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83
| class County(NamedModel):
| state = models.ForeignKey(State, models.CASCADE)
mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83
| from django.contrib.gis.db import models
class NamedModel(models.Model):
name = models.CharField(max_length=25)
class Meta:
abstract = True
def __str__(self):
return self.name
class State(NamedModel):
pass
class County(NamedModel):
| 62 | 64 | 42 | 6 | 55 | txf626/django | tests/gis_tests/layermap/models.py | Python | County | County | 18 | 20 | 18 | 18 | 00d0909341e3aa45307daa77977f11015237bcc6 | bigcode/the-stack | train |
e4388647b8c84e0501293d65 | train | class | class CityBase(NamedModel):
population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
point = models.PointField()
| class CityBase(NamedModel):
| population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
point = models.PointField()
| '
class Interstate(NamedModel):
length = models.DecimalField(max_digits=6, decimal_places=2)
path = models.LineStringField()
class Meta:
app_label = 'layermap'
# Same as `City` above, but for testing model inheritance.
class CityBase(NamedModel):
| 64 | 64 | 37 | 7 | 57 | txf626/django | tests/gis_tests/layermap/models.py | Python | CityBase | CityBase | 48 | 51 | 48 | 48 | 3e3e6226b65b9acae85220fffab4dc55c6cfe5da | bigcode/the-stack | train |
8fca748fef1e4b378c0048ac | train | class | class ICity1(CityBase):
dt = models.DateField()
class Meta(CityBase.Meta):
pass
| class ICity1(CityBase):
| dt = models.DateField()
class Meta(CityBase.Meta):
pass
| = 'layermap'
# Same as `City` above, but for testing model inheritance.
class CityBase(NamedModel):
population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
point = models.PointField()
class ICity1(CityBase):
| 64 | 64 | 26 | 8 | 56 | txf626/django | tests/gis_tests/layermap/models.py | Python | ICity1 | ICity1 | 54 | 58 | 54 | 54 | dd0a6597f1bfb5c6d8967818a9d5fb4ded025f32 | bigcode/the-stack | train |
2383d82ac9afb6f76b56b255 | train | class | class Interstate(NamedModel):
length = models.DecimalField(max_digits=6, decimal_places=2)
path = models.LineStringField()
class Meta:
app_label = 'layermap'
| class Interstate(NamedModel):
| length = models.DecimalField(max_digits=6, decimal_places=2)
path = models.LineStringField()
class Meta:
app_label = 'layermap'
| = models.CharField(max_length=5)
population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
dt = models.DateField()
point = models.PointField()
class Meta:
app_label = 'layermap'
class Interstate(NamedModel):
| 64 | 64 | 42 | 6 | 58 | txf626/django | tests/gis_tests/layermap/models.py | Python | Interstate | Interstate | 39 | 44 | 39 | 39 | 7fc703cf0088e5433f54b2258074819babe84525 | bigcode/the-stack | train |
d58753b177cd98dc8bee7cbc | train | class | class Invalid(models.Model):
point = models.PointField()
| class Invalid(models.Model):
| point = models.PointField()
| Field()
class ICity1(CityBase):
dt = models.DateField()
class Meta(CityBase.Meta):
pass
class ICity2(ICity1):
dt_time = models.DateTimeField(auto_now=True)
class Meta(ICity1.Meta):
pass
class Invalid(models.Model):
| 64 | 64 | 12 | 5 | 58 | txf626/django | tests/gis_tests/layermap/models.py | Python | Invalid | Invalid | 68 | 69 | 68 | 68 | 7792cb4e4f5817bb093bc5aa8622a57529d8d3cd | bigcode/the-stack | train |
b2c3d597ee724aaefb056ae1 | train | class | class CountyFeat(NamedModel):
poly = models.PolygonField(srid=4269)
| class CountyFeat(NamedModel):
| poly = models.PolygonField(srid=4269)
| ):
return self.name
class State(NamedModel):
pass
class County(NamedModel):
state = models.ForeignKey(State, models.CASCADE)
mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83
class CountyFeat(NamedModel):
| 64 | 64 | 20 | 7 | 56 | txf626/django | tests/gis_tests/layermap/models.py | Python | CountyFeat | CountyFeat | 23 | 24 | 23 | 23 | a520ab837b014d7656ebd08ede5d4289994a7499 | bigcode/the-stack | train |
92bd482b57e44b9c230b33a4 | train | class | class City(NamedModel):
name_txt = models.TextField(default='')
name_short = models.CharField(max_length=5)
population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
dt = models.DateField()
point = models.PointField()
class Meta:
app_label = 'l... | class City(NamedModel):
| name_txt = models.TextField(default='')
name_short = models.CharField(max_length=5)
population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
dt = models.DateField()
point = models.PointField()
class Meta:
app_label = 'layermap'
| Model):
state = models.ForeignKey(State, models.CASCADE)
mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83
class CountyFeat(NamedModel):
poly = models.PolygonField(srid=4269)
class City(NamedModel):
| 64 | 64 | 76 | 6 | 58 | txf626/django | tests/gis_tests/layermap/models.py | Python | City | City | 27 | 36 | 27 | 27 | a58bbc2138c39654075925fe81e9fd3972fb5efc | bigcode/the-stack | train |
5ba39f47e14fd1d0a68e83c5 | train | class | class State(NamedModel):
pass
| class State(NamedModel):
| pass
| from django.contrib.gis.db import models
class NamedModel(models.Model):
name = models.CharField(max_length=25)
class Meta:
abstract = True
def __str__(self):
return self.name
class State(NamedModel):
| 53 | 64 | 9 | 6 | 46 | txf626/django | tests/gis_tests/layermap/models.py | Python | State | State | 14 | 15 | 14 | 14 | 1873d92559e58f15bd3d1032199c8ebd9a745011 | bigcode/the-stack | train |
ec0fb0a3e8b3e79c88a38910 | train | function | def setup(hass, config):
"""Setup our skeleton component."""
# States are in the format DOMAIN.OBJECT_ID.
hass.states.set('goodbye.failing', 'JoeyChaps!')
hass.states.set('hello.success', config[DOMAIN]['from'])
_LOGGER.info("Consider yourself logged!")
# Return boolean to indicate that initial... | def setup(hass, config):
| """Setup our skeleton component."""
# States are in the format DOMAIN.OBJECT_ID.
hass.states.set('goodbye.failing', 'JoeyChaps!')
hass.states.set('hello.success', config[DOMAIN]['from'])
_LOGGER.info("Consider yourself logged!")
# Return boolean to indicate that initialization was successfully.... | _world:
"""
import logging
_LOGGER = logging.getLogger(__name__)
# The domain of your component. Should be equal to the name of your component.
DOMAIN = "hello_state"
# List of component names (string) your component depends upon.
DEPENDENCIES = []
def setup(hass, config):
| 63 | 64 | 80 | 7 | 56 | cyrus19901/home-assistant | config/custom_components/hello_state.py | Python | setup | setup | 25 | 33 | 25 | 25 | a4cb3d496297a092acb35338c1f4cd5cc03b88e8 | bigcode/the-stack | train |
2017abb238381f3da0375f85 | train | function | @app.task
def async_send_sms(to, datas, template_id):
"""异步发送短信验证码 注意结果不是直接返回,而是存到celery的backend中"""
result = CCP().send_template_sms(to, datas, template_id)
return result
| @app.task
def async_send_sms(to, datas, template_id):
| """异步发送短信验证码 注意结果不是直接返回,而是存到celery的backend中"""
result = CCP().send_template_sms(to, datas, template_id)
return result
| from django.conf import settings
from django.core.cache import caches
from django.core.mail import send_mail
from apps.user.models import User
from libs.yuntongxun.sms import CCP
from meiduoshop.celery import app
@app.task
def async_send_sms(to, datas, template_id):
| 64 | 64 | 55 | 14 | 49 | 1572990942/meiduoshop | meiduoshop/apps/verify/tasks.py | Python | async_send_sms | async_send_sms | 13 | 17 | 13 | 14 | aaead580d8e67e7379d2eeb9cb7fbe322f6b8b5c | bigcode/the-stack | train |
7f8ad8fd73fa4a0e89b3829a | train | class | class Dropdown(Component):
"""A Dropdown component.
Dropdown is an interactive dropdown element for selecting one or more
items.
The values and labels of the dropdown items are specified in the `options`
property and the selected item(s) are specified with the `value` property.
Use a dropdown when you have many op... | class Dropdown(Component):
| """A Dropdown component.
Dropdown is an interactive dropdown element for selecting one or more
items.
The values and labels of the dropdown items are specified in the `options`
property and the selected item(s) are specified with the `value` property.
Use a dropdown when you have many options (more than 5) or when... | # AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Dropdown(Component):
| 27 | 256 | 970 | 4 | 22 | AboorvaDevarajan/dash-core-components | dash_core_components/Dropdown.py | Python | Dropdown | Dropdown | 6 | 68 | 6 | 6 | 6d645eeccfcc3a1c4e8f0b3abef04eca1292026a | bigcode/the-stack | train |
db79d4081dc0c295cc6788d2 | train | class | class Section(object):
__module__ = "testrail_yak"
def __init__(self, api):
self.client = api
def get(self, section_id: int) -> dict:
"""Get test section from a test suite by section_id.
:param section_id: section ID to grab section from
:return: response from TestRail AP... | class Section(object):
| __module__ = "testrail_yak"
def __init__(self, api):
self.client = api
def get(self, section_id: int) -> dict:
"""Get test section from a test suite by section_id.
:param section_id: section ID to grab section from
:return: response from TestRail API containing the test se... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .lib.testrail import APIError
from .lib.schema import SectionSchema, SectionUpdateSchema, SchemaError
class Section(object):
| 43 | 256 | 984 | 4 | 38 | bbeale/TestRailYak | testrail_yak/section.py | Python | Section | Section | 7 | 132 | 7 | 8 | f29edc0efd882dd07db8fb9c063d96cf597bf779 | bigcode/the-stack | train |
ff1ff58a10163222743888c1 | train | class | class SectionException(Exception):
pass
| class SectionException(Exception):
| pass
| _id: int) -> dict:
"""Deletes an existing section. """
try:
result = self.client.send_post(f"delete_section/{section_id}", data=None)
except APIError as error:
print(error)
raise SectionException
else:
return result
class SectionException(E... | 64 | 64 | 8 | 5 | 58 | bbeale/TestRailYak | testrail_yak/section.py | Python | SectionException | SectionException | 135 | 136 | 135 | 135 | 057f824d1d9cdcd90ac2622e849863a785888602 | bigcode/the-stack | train |
f95292f4f3a7aeceb9d88779 | train | function | def isRotm(R) :
Rt = np.transpose(R)
shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype = R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
| def isRotm(R) :
| Rt = np.transpose(R)
shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype = R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
| math.cos(theta[2]), 0],
[0, 0, 1]
])
R = np.dot(R_z, np.dot( R_y, R_x ))
return R
# Checks if a matrix is a valid rotation matrix.
def isRotm(R) :
| 64 | 64 | 61 | 7 | 57 | esteng/guiding-multi-step | utils.py | Python | isRotm | isRotm | 666 | 671 | 666 | 666 | ebb19461fa0d596fb25bb2621c4f9d34a64a6637 | bigcode/the-stack | train |
cda068ff38a311041870cd1a | train | function | def common_sense_action_space_mask(depth_heightmap, push_predictions=None, grasp_predictions=None, place_predictions=None, place_dilation=None, show_heightmap=False, color_heightmap=None):
""" Convert predictions to a masked array indicating if tasks may make progress in this region, based on depth_heightmap.
... | def common_sense_action_space_mask(depth_heightmap, push_predictions=None, grasp_predictions=None, place_predictions=None, place_dilation=None, show_heightmap=False, color_heightmap=None):
| """ Convert predictions to a masked array indicating if tasks may make progress in this region, based on depth_heightmap.
The masked arrays will indicate 0 where progress may be possible (no mask applied), and 1 where our model confidently indicates no progress will be made.
Note the mask values here are t... | > (regional_maximums - z_buffer)).astype(np.uint8)
# set all the pixels where the push would be too high to zero,
# meaning it is not an action which would contact any object
# the blocks and the gripper width around them are set to zero.
gripper_width_pixels_to_dilate = int(np.ceil((gr... | 189 | 189 | 633 | 38 | 150 | esteng/guiding-multi-step | utils.py | Python | common_sense_action_space_mask | common_sense_action_space_mask | 214 | 255 | 214 | 214 | 4ba4bf63c3871f25a2d78889aacc4fb6b358c49a | bigcode/the-stack | train |
609aaadf4318ff68a53667f6 | train | function | def get_heightmap(color_img, depth_img, cam_intrinsics, cam_pose, workspace_limits, heightmap_resolution, background_heightmap=None, median_filter_pixels=5, color_median_filter_pixels=5):
""" Note:
Arg median_filter_pixels is used for the depth image.
Arg color_median_filter_pixels is used for the color ima... | def get_heightmap(color_img, depth_img, cam_intrinsics, cam_pose, workspace_limits, heightmap_resolution, background_heightmap=None, median_filter_pixels=5, color_median_filter_pixels=5):
| """ Note:
Arg median_filter_pixels is used for the depth image.
Arg color_median_filter_pixels is used for the color image.
"""
if median_filter_pixels > 0:
depth_img = ndimage.median_filter(depth_img, size=median_filter_pixels)
# Compute heightmap size
heightmap_size = np.round(((... | [1][2],depth_img/camera_intrinsics[1][1])
cam_pts_z = depth_img.copy()
cam_pts_x.shape = (im_h*im_w,1)
cam_pts_y.shape = (im_h*im_w,1)
cam_pts_z.shape = (im_h*im_w,1)
# Reshape image into colors for 3D point cloud
rgb_pts_r = color_img[:,:,0]
rgb_pts_g = color_img[:,:,1]
rgb_pts_b = col... | 256 | 256 | 1,029 | 43 | 212 | esteng/guiding-multi-step | utils.py | Python | get_heightmap | get_heightmap | 125 | 190 | 125 | 125 | 8b6230782da85815203bd0bc5e8537cb72e24f97 | bigcode/the-stack | train |
79608616277f46f6ebbbcad3 | train | function | def axxb(robotPose, markerPose, baseToCamera=True):
"""
Copyright (c) 2019, Hongtao Wu
AX=XB solver for eye-on base
Using the Park and Martin Method: https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=326576
Args:
- robotPose (list of 4x4 numpy array): poses (homogenous transformation) of the... | def axxb(robotPose, markerPose, baseToCamera=True):
| """
Copyright (c) 2019, Hongtao Wu
AX=XB solver for eye-on base
Using the Park and Martin Method: https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=326576
Args:
- robotPose (list of 4x4 numpy array): poses (homogenous transformation) of the robot end-effector in the robot base frame.
- m... | (4, numpy array): orientation in quaternion
Returns:
- homo_mat (4x4 numpy array): homogenenous transformation matrix
"""
rotm = quat2rotm(orn)
homo_mat = np.c_[rotm, np.reshape(pos, (3, 1))]
homo_mat = np.r_[homo_mat, [[0, 0, 0, 1]]]
return homo_mat
def axis_angle_and_translation_to_rig... | 256 | 256 | 868 | 14 | 241 | esteng/guiding-multi-step | utils.py | Python | axxb | axxb | 839 | 910 | 839 | 839 | 35ecbe8f363a25121998a0de0c3a3ea83cbb2bf8 | bigcode/the-stack | train |
57df5f5c8ddc1a8d4b4739b7 | train | function | def rotm2euler(R) :
assert(isRotm(R))
sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
singular = sy < 1e-6
if not singular :
x = math.atan2(R[2,1] , R[2,2])
y = math.atan2(-R[2,0], sy)
z = math.atan2(R[1,0], R[0,0])
else :
x = math.atan2(-R[1,2], R[1,1])
... | def rotm2euler(R) :
| assert(isRotm(R))
sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
singular = sy < 1e-6
if not singular :
x = math.atan2(R[2,1] , R[2,2])
y = math.atan2(-R[2,0], sy)
z = math.atan2(R[1,0], R[0,0])
else :
x = math.atan2(-R[1,2], R[1,1])
y = math.atan2(-R[2... | shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype = R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
# Calculates rotation matrix to euler angles
def rotm2euler(R) :
| 64 | 64 | 172 | 9 | 54 | esteng/guiding-multi-step | utils.py | Python | rotm2euler | rotm2euler | 675 | 691 | 675 | 676 | 79ea22aa606dfedcc861a2c3d8fa201248e0831e | bigcode/the-stack | train |
a92a554714f8eee671cb695e | train | function | def get_difference(color_heightmap, color_space, bg_color_heightmap):
color_space = np.concatenate((color_space, np.asarray([[0.0, 0.0, 0.0]])), axis=0)
color_space.shape = (color_space.shape[0], 1, 1, color_space.shape[1])
color_space = np.tile(color_space, (1, color_heightmap.shape[0], color_heightmap.sh... | def get_difference(color_heightmap, color_space, bg_color_heightmap):
| color_space = np.concatenate((color_space, np.asarray([[0.0, 0.0, 0.0]])), axis=0)
color_space.shape = (color_space.shape[0], 1, 1, color_space.shape[1])
color_space = np.tile(color_space, (1, color_heightmap.shape[0], color_heightmap.shape[1], 1))
# Normalize color heightmaps
color_heightmap = col... | _vis).astype(np.uint8)
if rotate_idx == best_pix_ind[0]:
affordance_vis = cv2.circle(affordance_vis, (int(best_pix_ind[2]), int(best_pix_ind[1])), 7, (0,0,255), 2)
if tmp_row_vis is None:
tmp_row_vis = affordance_vis
else:
tmp_row_vis =... | 151 | 151 | 504 | 15 | 135 | esteng/guiding-multi-step | utils.py | Python | get_difference | get_difference | 617 | 644 | 617 | 618 | 8071a0e5ade9dd37bb376a87397e1b54ad42cb49 | bigcode/the-stack | train |
ac453ad6158cbd3de56054f7 | train | class | class StackSequence(object):
def __init__(self, num_obj, goal_num_obj = None, is_goal_conditioned_task=True, trial=0, total_steps=1, color_names=None):
""" Oracle to choose a sequence of specific color objects to interact with.
Generates one hot encodings for a list of objects of the specified leng... | class StackSequence(object):
| def __init__(self, num_obj, goal_num_obj = None, is_goal_conditioned_task=True, trial=0, total_steps=1, color_names=None):
""" Oracle to choose a sequence of specific color objects to interact with.
Generates one hot encodings for a list of objects of the specified length.
Can be used for s... | : success
:rtype: bool
"""
for i in range(len(values) - 1):
x = values[i]
y = values[i + 1]
assert x < y, '`values` assumed to be sorted'
if y < x + small_distance_threshold / 2.:
# # print('check_separation(): not long enough for idx: {}'.format(i))
r... | 229 | 229 | 764 | 5 | 223 | esteng/guiding-multi-step | utils.py | Python | StackSequence | StackSequence | 1,011 | 1,088 | 1,011 | 1,011 | 97cca4749093c1f46ec5d873e4651f1ad25d315c | bigcode/the-stack | train |
b48fe19d9686c13c3cd52fef | train | function | def is_jsonable(x):
try:
json.dumps(x)
return True
except (TypeError, OverflowError):
return False
| def is_jsonable(x):
| try:
json.dumps(x)
return True
except (TypeError, OverflowError):
return False
| (*args, **kwargs):
with warnings.catch_warnings():
# suppress the RankWarning, which just means the best fit line was bad.
warnings.simplefilter('ignore', np.RankWarning)
out = np.polyfit(*args, **kwargs)
return out
def is_jsonable(x):
| 64 | 64 | 31 | 6 | 57 | esteng/guiding-multi-step | utils.py | Python | is_jsonable | is_jsonable | 1,003 | 1,008 | 1,003 | 1,003 | fed6ad2a455d46c8f42e85c1beac744e2f294e87 | bigcode/the-stack | train |
c66b5f131154f3561c1527fb | train | function | def axis_angle_and_translation_to_rigid_transformation(tool_position, tool_orientation):
tool_orientation_angle = np.linalg.norm(tool_orientation)
tool_orientation_axis = tool_orientation/tool_orientation_angle
# Note that this following rotm is the base frame in tool frame
tool_orientation_rotm = angle... | def axis_angle_and_translation_to_rigid_transformation(tool_position, tool_orientation):
| tool_orientation_angle = np.linalg.norm(tool_orientation)
tool_orientation_axis = tool_orientation/tool_orientation_angle
# Note that this following rotm is the base frame in tool frame
tool_orientation_rotm = angle2rotm(tool_orientation_angle, tool_orientation_axis, point=None)[:3,:3]
# Tool rigid ... | homo_mat = np.c_[rotm, np.reshape(pos, (3, 1))]
homo_mat = np.r_[homo_mat, [[0, 0, 0, 1]]]
return homo_mat
def axis_angle_and_translation_to_rigid_transformation(tool_position, tool_orientation):
| 64 | 64 | 150 | 16 | 47 | esteng/guiding-multi-step | utils.py | Python | axis_angle_and_translation_to_rigid_transformation | axis_angle_and_translation_to_rigid_transformation | 826 | 836 | 826 | 826 | 5d9745d7215684a41cc4e58d634b25f50541f5b9 | bigcode/the-stack | train |
514910f723b9ce371612c39a | train | function | def calib_grid_cartesian(workspace_limits, calib_grid_step):
"""
Construct 3D calibration grid across workspace
# Arguments
workspace_limits: list of [min,max] coordinates for the list [x, y, z] in meters.
calib_grid_step: the step size of points in a 3d grid to be created in meters.
... | def calib_grid_cartesian(workspace_limits, calib_grid_step):
| """
Construct 3D calibration grid across workspace
# Arguments
workspace_limits: list of [min,max] coordinates for the list [x, y, z] in meters.
calib_grid_step: the step size of points in a 3d grid to be created in meters.
# Returns
num_calib_grid_pts, calib_grid_pts
"""... | """
theta = np.arccos((np.trace(R) - 1) / 2)
w_hat = (R - R.T) * theta / (2 * np.sin(theta)) # Skew symmetric matrix
w = np.array([w_hat[2, 1], w_hat[0, 2], w_hat[1, 0]]) # [w1, w2, w3]
return w
def calib_grid_cartesian(workspace_limits, calib_grid_step):
| 108 | 108 | 361 | 13 | 94 | esteng/guiding-multi-step | utils.py | Python | calib_grid_cartesian | calib_grid_cartesian | 949 | 971 | 949 | 949 | 0c9e18a8e92aca28466e07172fa6b99f278877bb | bigcode/the-stack | train |
8433622b19dcc5ecad9f43fb | train | function | def rotm2angle(R):
# From: euclideanspace.com
epsilon = 0.01 # Margin to allow for rounding errors
epsilon2 = 0.1 # Margin to distinguish between 0 and 180 degrees
assert(isRotm(R))
if ((abs(R[0][1]-R[1][0])< epsilon) and (abs(R[0][2]-R[2][0])< epsilon) and (abs(R[1][2]-R[2][1])< epsilon)):
... | def rotm2angle(R):
# From: euclideanspace.com
| epsilon = 0.01 # Margin to allow for rounding errors
epsilon2 = 0.1 # Margin to distinguish between 0 and 180 degrees
assert(isRotm(R))
if ((abs(R[0][1]-R[1][0])< epsilon) and (abs(R[0][2]-R[2][0])< epsilon) and (abs(R[1][2]-R[2][1])< epsilon)):
# Singularity found
# First check for id... | 2018, Christoph Gohlke
sina = math.sin(angle)
cosa = math.cos(angle)
axis_magnitude = np.linalg.norm(axis)
axis = np.divide(axis, axis_magnitude, out=np.zeros_like(axis), where=axis_magnitude!=0)
# Rotation matrix around unit vector
R = np.diag([cosa, cosa, cosa])
R += np.array(np.outer(ax... | 256 | 256 | 892 | 18 | 237 | esteng/guiding-multi-step | utils.py | Python | rotm2angle | rotm2angle | 720 | 783 | 720 | 722 | 1bce5290c177f06eab6dc8ca6d32743c371314bb | bigcode/the-stack | train |
9bb80b758721e22fa163174a | train | class | class NumpyEncoder(json.JSONEncoder):
""" json encoder for numpy types
source: https://stackoverflow.com/a/49677241/99379
"""
def default(self, obj):
if isinstance(obj,
(np.int_, np.intc, np.intp, np.int8,
np.int16, np.int32, np.int64, np.uint8,
np.uint16, n... | class NumpyEncoder(json.JSONEncoder):
| """ json encoder for numpy types
source: https://stackoverflow.com/a/49677241/99379
"""
def default(self, obj):
if isinstance(obj,
(np.int_, np.intc, np.intp, np.int8,
np.int16, np.int32, np.int64, np.uint8,
np.uint16, np.uint32, np.uint64)):
ret... | d-%H-%M-%S_{fname}'):
""" Apply a timestamp to the front of a filename description.
see: http://stackoverflow.com/a/5215012/99379
"""
return datetime.datetime.now().strftime(fmt).format(fname=fname)
class NumpyEncoder(json.JSONEncoder):
| 64 | 64 | 151 | 8 | 56 | esteng/guiding-multi-step | utils.py | Python | NumpyEncoder | NumpyEncoder | 57 | 73 | 57 | 57 | 8994b49f729074247f6a328692b01f84a6f58784 | bigcode/the-stack | train |
ec4fb2395c5764c39bd54922 | train | function | def process_prediction_language_masking(language_data, predictions, show_heightmap=False, color_heightmap=None, tile_size = 4, threshold = 0.9, single_max = True, abs_threshold = 0.10, from_transformer = True, baseline_language_mask = False):
"""
Adds a language mask to the predictions array.
language_data... | def process_prediction_language_masking(language_data, predictions, show_heightmap=False, color_heightmap=None, tile_size = 4, threshold = 0.9, single_max = True, abs_threshold = 0.10, from_transformer = True, baseline_language_mask = False):
| """
Adds a language mask to the predictions array.
language_data: an array with shape [1, 256, 2, 1] which will be processed into a mask
predictions: masked array or ndarray with prediction values for a specific action
"""
# Convert inputs to np.ma.masked_array objects if they are inputted as ... | ipper_width=place_dilation)
place_predictions = np.ma.masked_array(place_predictions, np.broadcast_to(1 - place_contact_regions, push_predictions.shape, subok=True))
if show_heightmap:
# visualize the common sense function results
# show the heightmap
f = plt.figure()
# f.sup... | 256 | 256 | 1,173 | 59 | 196 | esteng/guiding-multi-step | utils.py | Python | process_prediction_language_masking | process_prediction_language_masking | 258 | 356 | 258 | 258 | 559dee0c675095732f32c231bb46fade49c84b84 | bigcode/the-stack | train |
cbcea69d0bb2433d94a082db | train | function | def load_language_model_from_config(configYamlPath, weightsPath):
# Load config yaml file if possible
if os.path.exists(configYamlPath):
with open(configYamlPath) as file:
config=yaml.load(file, Loader=yaml.FullLoader)
else:
raise FileNotFoundError(f'unable to find {configYamlPa... | def load_language_model_from_config(configYamlPath, weightsPath):
# Load config yaml file if possible
| if os.path.exists(configYamlPath):
with open(configYamlPath) as file:
config=yaml.load(file, Loader=yaml.FullLoader)
else:
raise FileNotFoundError(f'unable to find {configYamlPath}')
# Move model to available gpu
device = "cpu"
if config["cuda"] is not None and config["c... | language_output
next_pos = next_pos['next_position']
prev_pos = prev_pos['next_position']
from_transformer = False
else:
prev_pos, next_pos = language_output['prev_position'], language_output['next_position']
if baseline_language_mask:
print(f"RUNNING RANDOM BASELINE FO... | 256 | 256 | 1,083 | 22 | 233 | esteng/guiding-multi-step | utils.py | Python | load_language_model_from_config | load_language_model_from_config | 454 | 560 | 454 | 456 | 7d30e2310586b90232ad2eb73ab059f0dcc7418e | bigcode/the-stack | train |
225f0012fe9d91f7f0996d34 | train | function | def get_pointcloud(color_img, depth_img, camera_intrinsics):
# Get depth image size
im_h = depth_img.shape[0]
im_w = depth_img.shape[1]
# Project depth into 3D point cloud in camera coordinates
pix_x,pix_y = np.meshgrid(np.linspace(0,im_w-1,im_w), np.linspace(0,im_h-1,im_h))
cam_pts_x = np.mul... | def get_pointcloud(color_img, depth_img, camera_intrinsics):
# Get depth image size
| im_h = depth_img.shape[0]
im_w = depth_img.shape[1]
# Project depth into 3D point cloud in camera coordinates
pix_x,pix_y = np.meshgrid(np.linspace(0,im_w-1,im_w), np.linspace(0,im_h-1,im_h))
cam_pts_x = np.multiply(pix_x-camera_intrinsics[0][2],depth_img/camera_intrinsics[0][0])
cam_pts_y = np... | _log).astype(np.int)
# Make a list of the right length containing all zeros
trial_count = []
prev_trial_end_index = 0
for trial_num, trial_end_index in enumerate(clearance_log):
trial_count += [[trial_num]] * int(trial_end_index - prev_trial_end_index)
prev_trial_end_index = trial_end_in... | 103 | 103 | 346 | 21 | 81 | esteng/guiding-multi-step | utils.py | Python | get_pointcloud | get_pointcloud | 96 | 122 | 96 | 98 | ad974b8ee7474fa894fc2ec9feaa5268f3c51f03 | bigcode/the-stack | train |
6f3fb5770e7b17ddf18c3886 | train | function | def make_rigid_transformation(pos, orn):
"""
Rigid transformation from position and orientation.
Args:
- pos (3, numpy array): translation
- orn (4, numpy array): orientation in quaternion
Returns:
- homo_mat (4x4 numpy array): homogenenous transformation matrix
"""
rotm = quat2rotm(... | def make_rigid_transformation(pos, orn):
| """
Rigid transformation from position and orientation.
Args:
- pos (3, numpy array): translation
- orn (4, numpy array): orientation in quaternion
Returns:
- homo_mat (4x4 numpy array): homogenenous transformation matrix
"""
rotm = quat2rotm(orn)
homo_mat = np.c_[rotm, np.reshap... | , 2*(y*z-x*w)/s ],
[2*(x*z-y*w)/s, 2*(y*z+x*w)/s, 1-2*(x*x+y*y)/s]
])
return rotm
def make_rigid_transformation(pos, orn):
| 64 | 64 | 130 | 10 | 53 | esteng/guiding-multi-step | utils.py | Python | make_rigid_transformation | make_rigid_transformation | 810 | 823 | 810 | 810 | 0886d4327b71eeeda328984b8de2c452678aea3f | bigcode/the-stack | train |
fbc4c5d857d62243b820e8ab | train | function | def pcwrite(xyz_pts, filename, rgb_pts=None):
assert xyz_pts.shape[1] == 3, 'input XYZ points should be an Nx3 matrix'
if rgb_pts is None:
rgb_pts = np.ones(xyz_pts.shape).astype(np.uint8)*255
assert xyz_pts.shape == rgb_pts.shape, 'input RGB colors should be Nx3 matrix and same size as input XYZ po... | def pcwrite(xyz_pts, filename, rgb_pts=None):
| assert xyz_pts.shape[1] == 3, 'input XYZ points should be an Nx3 matrix'
if rgb_pts is None:
rgb_pts = np.ones(xyz_pts.shape).astype(np.uint8)*255
assert xyz_pts.shape == rgb_pts.shape, 'input RGB colors should be Nx3 matrix and same size as input XYZ points'
# Write header for .ply file
pc... | _kwargs)
# Load weights
print(f'loading model weights from {config["checkpoint_dir"]}')
state_dict = torch.load(pathlib.Path(config["checkpoint_dir"]).joinpath("best.th"), map_location = device)
encoder.load_state_dict(state_dict, strict=True)
return encoder
# Save a 3D point cloud to a binary ... | 91 | 91 | 305 | 13 | 77 | esteng/guiding-multi-step | utils.py | Python | pcwrite | pcwrite | 563 | 585 | 563 | 563 | c2d8492983f8fe3cace807bf7d133c0010f410b1 | bigcode/the-stack | train |
753354658137f4506a4ebd9d | train | function | def quat2rotm(quat):
"""
Quaternion to rotation matrix.
Args:
- quat (4, numpy array): quaternion w, x, y, z
Returns:
- rotm: (3x3 numpy array): rotation matrix
"""
w = quat[0]
x = quat[1]
y = quat[2]
z = quat[3]
s = w*w + x*x + y*y + z*z
rotm = np.array([[1-2*(y*y... | def quat2rotm(quat):
| """
Quaternion to rotation matrix.
Args:
- quat (4, numpy array): quaternion w, x, y, z
Returns:
- rotm: (3x3 numpy array): rotation matrix
"""
w = quat[0]
x = quat[1]
y = quat[2]
z = quat[3]
s = w*w + x*x + y*y + z*z
rotm = np.array([[1-2*(y*y+z*z)/s, 2*(x*y-z*w)/... | ][1] - R[1][2])/s
y = (R[0][2] - R[2][0])/s
z = (R[1][0] - R[0][1])/s
return [angle,x,y,z]
def quat2rotm(quat):
| 66 | 66 | 220 | 8 | 58 | esteng/guiding-multi-step | utils.py | Python | quat2rotm | quat2rotm | 786 | 807 | 786 | 786 | 16099dc43bf9321918b365b056d4269dedff4c58 | bigcode/the-stack | train |
368b9bf32803e5dab7ebab11 | train | function | def euler2rotm(theta):
R_x = np.array([[1, 0, 0 ],
[0, math.cos(theta[0]), -math.sin(theta[0]) ],
[0, math.sin(theta[0]), math.cos(theta[0]) ]
])
R_y = np.array([[math.cos(theta[1]), 0, ... | def euler2rotm(theta):
| R_x = np.array([[1, 0, 0 ],
[0, math.cos(theta[0]), -math.sin(theta[0]) ],
[0, math.sin(theta[0]), math.cos(theta[0]) ]
])
R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1]) ]... | - 1] = color_space.shape[0] + 2
return np.sum(key_color_match == bg_key_color_match).astype(float)/np.sum(bg_key_color_match < color_space.shape[0]).astype(float)
# Get rotation matrix from euler angles
def euler2rotm(theta):
| 64 | 64 | 207 | 8 | 55 | esteng/guiding-multi-step | utils.py | Python | euler2rotm | euler2rotm | 648 | 662 | 648 | 648 | 8c8ebe29edbfa698098f4cbdd7ae54cbf42f19b6 | bigcode/the-stack | train |
4e57ad869eaf0c58be87b4f2 | train | function | def compute_demo_dist(preds, example_actions, metric='l2'):
"""
Function to evaluate l2 distance and generate demo-signal mask
"""
# TODO(adit98) see if we should use cos_sim instead of l2_distance as low-level distance metric
def cos_sim(test_feat, demo_action_embed):
"""
Helper fu... | def compute_demo_dist(preds, example_actions, metric='l2'):
| """
Function to evaluate l2 distance and generate demo-signal mask
"""
# TODO(adit98) see if we should use cos_sim instead of l2_distance as low-level distance metric
def cos_sim(test_feat, demo_action_embed):
"""
Helper function to compute cosine similarity.
Arguments:
... | 224 (or whatever image size is), and color
prediction_vis = cv2.applyColorMap((predictions*255).astype(np.uint8), cv2.COLORMAP_JET)
# need to flip best_pix_ind row and col since cv2.circle reads in as (x, y)
prediction_vis = cv2.circle(prediction_vis, (int(best_action_xy[1]), int(best_action_xy... | 256 | 256 | 1,016 | 15 | 240 | esteng/guiding-multi-step | utils.py | Python | compute_demo_dist | compute_demo_dist | 1,244 | 1,364 | 1,244 | 1,244 | 343d1e7d24bc49cbd0e2f7a5a0f6ce620028b24a | bigcode/the-stack | train |
825507534bd80f8ef9a4d63b | train | function | def compute_cc_dist(test_preds, demo_preds):
"""
Function to evaluate l2 distance and generate demo-signal mask
"""
# TODO(adit98) see if we should use cos_sim instead of l2_distance as low-level distance metric
def cos_sim(pix_preds, best_pred):
"""
Helper function to compute cosin... | def compute_cc_dist(test_preds, demo_preds):
| """
Function to evaluate l2 distance and generate demo-signal mask
"""
# TODO(adit98) see if we should use cos_sim instead of l2_distance as low-level distance metric
def cos_sim(pix_preds, best_pred):
"""
Helper function to compute cosine similarity.
Arguments:
... | .unravel_index(np.argmin(dists), dists.shape)
else:
# find overall maximum similarity across all policies and get index
match_ind = np.unravel_index(np.argmax(dists), dists.shape)
#print("Selected match_ind:", match_ind)
# select distance array for policy which contained minimum distance i... | 228 | 228 | 760 | 10 | 217 | esteng/guiding-multi-step | utils.py | Python | compute_cc_dist | compute_cc_dist | 1,367 | 1,454 | 1,367 | 1,367 | 46cc27f836f37796f129863454d23aeaed2af766 | bigcode/the-stack | train |
ff2bf0492fa9d10582034902 | train | function | def mkdir_p(path):
"""Create the specified path on the filesystem like the `mkdir -p` command
Creates one or more filesystem directory levels as needed,
and does not return an error if the directory already exists.
"""
# http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
t... | def mkdir_p(path):
| """Create the specified path on the filesystem like the `mkdir -p` command
Creates one or more filesystem directory levels as needed,
and does not return an error if the directory already exists.
"""
# http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
try:
os.make... | action names to the corresponding ID number and vice-versa
ACTION_TO_ID = {'push': 0, 'grasp': 1, 'place': 2}
ID_TO_ACTION = {0: 'push', 1: 'grasp', 2: 'place'}
def mkdir_p(path):
| 63 | 64 | 115 | 5 | 58 | esteng/guiding-multi-step | utils.py | Python | mkdir_p | mkdir_p | 35 | 47 | 35 | 35 | e74b83ec3a4fa97e5ba21be96510665a6ae7b684 | bigcode/the-stack | train |
83354d62457379bb4c2e08fe | train | function | def clearance_log_to_trial_count(clearance_log):
""" Convert clearance log list of end indices to a list of the current trial number at each iteration.
# Returns
List of lists of the current trial index.
ex: [[0], [0], [0], [1], [1]]
"""
if not len(clearance_log):
return []
clearan... | def clearance_log_to_trial_count(clearance_log):
| """ Convert clearance log list of end indices to a list of the current trial number at each iteration.
# Returns
List of lists of the current trial index.
ex: [[0], [0], [0], [1], [1]]
"""
if not len(clearance_log):
return []
clearance_log = np.squeeze(clearance_log).astype(np.int)... | )
elif isinstance(obj,
(np.float_, np.float16, np.float32,
np.float64)):
return float(obj)
elif isinstance(obj, (np.ndarray,)):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
def clearance_log_to_trial_count(clearance_log):
| 64 | 64 | 166 | 10 | 54 | esteng/guiding-multi-step | utils.py | Python | clearance_log_to_trial_count | clearance_log_to_trial_count | 76 | 93 | 76 | 76 | ebc532a0d02ac658e3ba0db825f6dc20b2263fc3 | bigcode/the-stack | train |
f591bd3d55452a3e5fb5c739 | train | function | def check_separation(values, distance_threshold, small_distance_threshold = 0.05):
"""Checks that the separation among the values is close enough about distance_threshold.
:param values: array of values to check, assumed to be sorted from low to high
:param distance_threshold: threshold
:returns: succe... | def check_separation(values, distance_threshold, small_distance_threshold = 0.05):
| """Checks that the separation among the values is close enough about distance_threshold.
:param values: array of values to check, assumed to be sorted from low to high
:param distance_threshold: threshold
:returns: success
:rtype: bool
"""
for i in range(len(values) - 1):
x = value... | (num_calib_grid_pts,1)
calib_grid_pts = np.concatenate((calib_grid_x, calib_grid_y, calib_grid_z), axis=1)
return num_calib_grid_pts, calib_grid_pts
def check_separation(values, distance_threshold, small_distance_threshold = 0.05):
| 64 | 64 | 186 | 18 | 45 | esteng/guiding-multi-step | utils.py | Python | check_separation | check_separation | 974 | 993 | 974 | 974 | ae07b6c12fab0a32bbbb68a5f66fea4cb0d0072e | bigcode/the-stack | train |
3b4d467392f7216970d1f175 | train | function | def annotate_success_manually(command, prev_image, next_image):
"""
# Returns
description, comment.
"""
print(
"\nPress a key to label the file: 1. success, 2. failure, 3. skip \n"
"What to look for:\n"
" - A successful stack is 3 blocks tall or 4 blocks tall with the grip... | def annotate_success_manually(command, prev_image, next_image):
| """
# Returns
description, comment.
"""
print(
"\nPress a key to label the file: 1. success, 2. failure, 3. skip \n"
"What to look for:\n"
" - A successful stack is 3 blocks tall or 4 blocks tall with the gripper completely removed from the field of view.\n"
" - If... | .shape)
# select distance array for policy which contained minimum distance index
l2_dist = l2_dists[match_ind[0]]
# discard first dimension of match_ind to get it in the form (theta, y, x)
match_ind = match_ind[1:]
# make l2_dist >=0 and max_normalize
l2_dist = l2_dist - np.min(l2_dist)
... | 150 | 150 | 503 | 13 | 136 | esteng/guiding-multi-step | utils.py | Python | annotate_success_manually | annotate_success_manually | 1,456 | 1,504 | 1,456 | 1,456 | c41060e5ab3d3a8bf74defdf01df67c649d814d1 | bigcode/the-stack | train |
b4b7162d12f9cc51d89f133e | train | function | def common_sense_action_failure_heuristic(heightmap, heightmap_resolution=0.002, gripper_width=0.06, min_contact_height=0.02, push_length=0.0, z_buffer=0.01):
""" Get heuristic scores for the grasp Q value at various pixels. 0 means our model confidently indicates no progress will be made, 1 means progress may be p... | def common_sense_action_failure_heuristic(heightmap, heightmap_resolution=0.002, gripper_width=0.06, min_contact_height=0.02, push_length=0.0, z_buffer=0.01):
| """ Get heuristic scores for the grasp Q value at various pixels. 0 means our model confidently indicates no progress will be made, 1 means progress may be possible.
"""
pixels_to_dilate = int(np.ceil((gripper_width + push_length)/heightmap_resolution))
kernel = np.ones((pixels_to_dilate, pixels_to_dila... | )
color_heightmap_g = ndimage.median_filter(color_heightmap_g, size=color_median_filter_pixels)
color_heightmap = np.concatenate((color_heightmap_r, color_heightmap_g, color_heightmap_b), axis=2)
return color_heightmap, depth_heightmap
def common_sense_action_failure_heuristic(heightmap, heightmap_res... | 111 | 111 | 371 | 50 | 60 | esteng/guiding-multi-step | utils.py | Python | common_sense_action_failure_heuristic | common_sense_action_failure_heuristic | 192 | 212 | 192 | 192 | b6de7700399c04fceab333b4a18b1851f9cfcbe4 | bigcode/the-stack | train |
a567144780acc789056181c6 | train | function | def get_affordance_vis(grasp_affordances, input_images, num_rotations, best_pix_ind):
vis = None
for vis_row in range(num_rotations/4):
tmp_row_vis = None
for vis_col in range(4):
rotate_idx = vis_row*4+vis_col
affordance_vis = grasp_affordances[rotate_idx,:,:]
... | def get_affordance_vis(grasp_affordances, input_images, num_rotations, best_pix_ind):
| vis = None
for vis_row in range(num_rotations/4):
tmp_row_vis = None
for vis_col in range(4):
rotate_idx = vis_row*4+vis_col
affordance_vis = grasp_affordances[rotate_idx,:,:]
affordance_vis[affordance_vis < 0] = 0 # assume probability
# affordance... | pc_file.write('property uchar blue\n')
pc_file.write('end_header\n')
# Write 3D points to .ply file
for i in range(xyz_pts.shape[0]):
pc_file.write(bytearray(struct.pack("fffccc",xyz_pts[i][0],xyz_pts[i][1],xyz_pts[i][2],rgb_pts[i][0].tostring(),rgb_pts[i][1].tostring(),rgb_pts[i][2].tostring()... | 128 | 128 | 427 | 23 | 105 | esteng/guiding-multi-step | utils.py | Python | get_affordance_vis | get_affordance_vis | 588 | 614 | 588 | 588 | 45a8b48c61d8dfa71452e54d5a72984929c924f8 | bigcode/the-stack | train |
6df8d89735de410351116ac0 | train | function | def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
""" Apply a timestamp to the front of a filename description.
see: http://stackoverflow.com/a/5215012/99379
"""
return datetime.datetime.now().strftime(fmt).format(fname=fname)
| def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
| """ Apply a timestamp to the front of a filename description.
see: http://stackoverflow.com/a/5215012/99379
"""
return datetime.datetime.now().strftime(fmt).format(fname=fname)
| (path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
| 64 | 64 | 67 | 22 | 41 | esteng/guiding-multi-step | utils.py | Python | timeStamped | timeStamped | 50 | 54 | 50 | 50 | 3fd39a067bf904f0c7be12ae01ad5c978a49ec33 | bigcode/the-stack | train |
455038025816f2072e8bb01c | train | function | def pose_inv(pose):
"""
Inverse of a homogenenous transformation.
Args:
- pose (4x4 numpy array)
Return:
- inv_pose (4x4 numpy array)
"""
R = pose[:3, :3]
t = pose[:3, 3]
inv_R = R.T
inv_t = - np.dot(inv_R, t)
inv_pose = np.c_[inv_R, np.transpose(inv_t)]
inv_pose = ... | def pose_inv(pose):
| """
Inverse of a homogenenous transformation.
Args:
- pose (4x4 numpy array)
Return:
- inv_pose (4x4 numpy array)
"""
R = pose[:3, :3]
t = pose[:3, 3]
inv_R = R.T
inv_t = - np.dot(inv_R, t)
inv_pose = np.c_[inv_R, np.transpose(inv_t)]
inv_pose = np.r_[inv_pose, [[0,... | _Ra_Left, ta_Rtb_Right, rcond=None)[0]
cam2base = np.c_[R, t]
cam2base = np.r_[cam2base, [[0, 0, 0, 1]]]
return cam2base
def pose_inv(pose):
| 64 | 64 | 129 | 6 | 57 | esteng/guiding-multi-step | utils.py | Python | pose_inv | pose_inv | 913 | 930 | 913 | 913 | e2259322e50aff3d7a15343aa946a0c979a71fd0 | bigcode/the-stack | train |
dd404ee2e48d923b4ed71931 | train | function | def angle2rotm(angle, axis, point=None):
# Copyright (c) 2006-2018, Christoph Gohlke
sina = math.sin(angle)
cosa = math.cos(angle)
axis_magnitude = np.linalg.norm(axis)
axis = np.divide(axis, axis_magnitude, out=np.zeros_like(axis), where=axis_magnitude!=0)
# Rotation matrix around unit vector... | def angle2rotm(angle, axis, point=None):
# Copyright (c) 2006-2018, Christoph Gohlke
| sina = math.sin(angle)
cosa = math.cos(angle)
axis_magnitude = np.linalg.norm(axis)
axis = np.divide(axis, axis_magnitude, out=np.zeros_like(axis), where=axis_magnitude!=0)
# Rotation matrix around unit vector
R = np.diag([cosa, cosa, cosa])
R += np.array(np.outer(axis, axis) * (1.0 - cosa)... | math.atan2(-R[1,2], R[1,1])
y = math.atan2(-R[2,0], sy)
z = 0
return np.array([x, y, z])
def angle2rotm(angle, axis, point=None):
# Copyright (c) 2006-2018, Christoph Gohlke
| 78 | 78 | 260 | 30 | 48 | esteng/guiding-multi-step | utils.py | Python | angle2rotm | angle2rotm | 694 | 717 | 694 | 696 | 5f07642db4eac099adfa5623df7bebab1534c5dc | bigcode/the-stack | train |
5cf49b1258f2bb68b814ad6a | train | function | def infect_mask(language_mask, curr_mask, block_width = 16):
# expand out from intersection: if any pixel of a block is yes under language mask, then whole block should be yes
curr_mask = 1 - curr_mask
intersection_mask = np.logical_and(curr_mask, language_mask).astype(float)
# use inf as sentinel valu... | def infect_mask(language_mask, curr_mask, block_width = 16):
# expand out from intersection: if any pixel of a block is yes under language mask, then whole block should be yes
| curr_mask = 1 - curr_mask
intersection_mask = np.logical_and(curr_mask, language_mask).astype(float)
# use inf as sentinel value
orig_intersection_mask = intersection_mask.copy()
intersection_mask *= 1000
# top-down, left to right across mask
language_mask = language_mask[0]
curr_mask =... | .subplots(2,3)
ax[0,0].imshow(curr_mask[0,:,:])
ax[0,1].imshow(1 - language_mask_before)
ax[0,2].imshow(predictions.mask[0,:,:])
# ax[1,0].imshow((curr_mask[0,:,:] + 1 - language_mask[0,:,:])/2)
ax[1,0].imshow((curr_mask[0,:,:] + 1 - language_mask_before)/2)
if color_hei... | 175 | 175 | 584 | 41 | 133 | esteng/guiding-multi-step | utils.py | Python | infect_mask | infect_mask | 358 | 418 | 358 | 359 | db8e3d20d806dcb3fe27115edd2c8d4ce4228231 | bigcode/the-stack | train |
8eb7302f0c2576847097965b | train | function | def check_row_success(depth_heightmap, block_height_threshold=0.02, row_boundary_length=75, row_boundary_width=18, block_pixel_size=550, prev_z_height=None):
""" Return if the current arrangement of blocks in the heightmap is a valid row
"""
heightmap_trans = np.copy(depth_heightmap)
heightmap_trans = n... | def check_row_success(depth_heightmap, block_height_threshold=0.02, row_boundary_length=75, row_boundary_width=18, block_pixel_size=550, prev_z_height=None):
| """ Return if the current arrangement of blocks in the heightmap is a valid row
"""
heightmap_trans = np.copy(depth_heightmap)
heightmap_trans = np.transpose(heightmap_trans)
heightmaps = (depth_heightmap, heightmap_trans)
counts = []
for heightmap in heightmaps:
# threshold pixels... | of the current stacking sequence we have completed.
For example, if the sequence should be [0, 1, 3, 2].
At initialization this will return [0].
After one next() calls it will return [0, 1].
After two next() calls it will return [0, 1, 3].
After three next() calls it will retur... | 232 | 232 | 776 | 39 | 193 | esteng/guiding-multi-step | utils.py | Python | check_row_success | check_row_success | 1,091 | 1,161 | 1,091 | 1,091 | 3e47883258fb8f9c55fbf94d4200a8afd0aba883 | bigcode/the-stack | train |
bb1a2a71a34f49d51617d1df | train | function | def get_mat_log(R):
"""
Get the log(R) of the rotation matrix R.
Args:
- R (3x3 numpy array): rotation matrix
Returns:
- w (3, numpy array): log(R)
"""
theta = np.arccos((np.trace(R) - 1) / 2)
w_hat = (R - R.T) * theta / (2 * np.sin(theta)) # Skew symmetric matrix
w = np.array(... | def get_mat_log(R):
| """
Get the log(R) of the rotation matrix R.
Args:
- R (3x3 numpy array): rotation matrix
Returns:
- w (3, numpy array): log(R)
"""
theta = np.arccos((np.trace(R) - 1) / 2)
w_hat = (R - R.T) * theta / (2 * np.sin(theta)) # Skew symmetric matrix
w = np.array([w_hat[2, 1], w_hat[... | R.T
inv_t = - np.dot(inv_R, t)
inv_pose = np.c_[inv_R, np.transpose(inv_t)]
inv_pose = np.r_[inv_pose, [[0, 0, 0, 1]]]
return inv_pose
def get_mat_log(R):
| 64 | 64 | 146 | 6 | 57 | esteng/guiding-multi-step | utils.py | Python | get_mat_log | get_mat_log | 933 | 946 | 933 | 933 | b1d0ecf44bd3246faff7e3f5884e64fba7f44a5f | bigcode/the-stack | train |
83762d66bd747cff1b3b669d | train | function | def common_sense_language_model_mask(language_output, push_predictions=None, grasp_predictions=None, place_predictions=None, color_heightmap=None, check_row = False, baseline_language_mask = False):
"""
Processes the language output into a mask and combine it with existing masks in prediction arrays
"""
... | def common_sense_language_model_mask(language_output, push_predictions=None, grasp_predictions=None, place_predictions=None, color_heightmap=None, check_row = False, baseline_language_mask = False):
| """
Processes the language output into a mask and combine it with existing masks in prediction arrays
"""
# language masks are currently for grasp and place only. The push predictions will not be operated upon.
# (elias) makes push illegal
#push_predictions = 1 - push_predictions * np.inf
... | 1))
# fig, ax = plt.subplots(1,2)
# ax[0].imshow(orig_intersection_mask[0,:,:])
# ax[1].imshow(curr_mask[0,:,:])
# plt.show(block=True)
return 1 - curr_mask
# TODO(zhe) implement language model masking using language model output. The inputs should already be np.masked_arrays
def common_sense_lang... | 120 | 120 | 402 | 38 | 81 | esteng/guiding-multi-step | utils.py | Python | common_sense_language_model_mask | common_sense_language_model_mask | 422 | 451 | 422 | 422 | e5ef7688044fbe3fb8313a149bb8eb6026504c89 | bigcode/the-stack | train |
67cf6311374fc3f86b7f270b | train | function | def get_prediction_vis(predictions, heightmap, best_pix_ind, blend_ratio=0.5, \
prob_exp=1, specific_rotation=None, num_rotations=None):
best_rot_ind = best_pix_ind[0]
best_action_xy = best_pix_ind[1:]
canvas = None
# clip values <0 or >1
predictions = np.clip(predictions, 0, 1)
# app... | def get_prediction_vis(predictions, heightmap, best_pix_ind, blend_ratio=0.5, \
prob_exp=1, specific_rotation=None, num_rotations=None):
| best_rot_ind = best_pix_ind[0]
best_action_xy = best_pix_ind[1:]
canvas = None
# clip values <0 or >1
predictions = np.clip(predictions, 0, 1)
# apply exponential
predictions = predictions ** prob_exp
if specific_rotation is None:
num_rotations = predictions.shape[0]
... | _r,y2_r],[x3_r,y3_r],[x4_r,y4_r]], np.int32)
pts = pts.reshape((-1,1,2))
cv2.fillPoly(mask, [pts], (255,255,255))
mask = mask > 0 # convert to bool
# get all block_pixels inside of row_boundary_rectangle and count them
block_pixels_in_row = np.logical_and(mask, block_pixels)
... | 247 | 247 | 824 | 37 | 210 | esteng/guiding-multi-step | utils.py | Python | get_prediction_vis | get_prediction_vis | 1,164 | 1,242 | 1,164 | 1,166 | dcfd51aedd278c58eb4b202915d699d9b3af700f | bigcode/the-stack | train |
ff07e2168efd368d8e05c0ec | train | function | def polyfit(*args, **kwargs):
with warnings.catch_warnings():
# suppress the RankWarning, which just means the best fit line was bad.
warnings.simplefilter('ignore', np.RankWarning)
out = np.polyfit(*args, **kwargs)
return out
| def polyfit(*args, **kwargs):
| with warnings.catch_warnings():
# suppress the RankWarning, which just means the best fit line was bad.
warnings.simplefilter('ignore', np.RankWarning)
out = np.polyfit(*args, **kwargs)
return out
| # # print('check_separation(): not long enough for idx: {}'.format(i))
return False
if abs(y - x) > distance_threshold:
# print('check_separation(): too far apart')
return False
return True
def polyfit(*args, **kwargs):
| 64 | 64 | 61 | 9 | 54 | esteng/guiding-multi-step | utils.py | Python | polyfit | polyfit | 996 | 1,001 | 996 | 996 | defcbeef5b68048a0a713ec74d96ec9f98476fbf | bigcode/the-stack | train |
559252c8015cd1388aa060e9 | train | class | class ObjectColorSource(Enum, IComparable, IFormattable, IConvertible):
"""
Defines enumerated values for the source of display color of single objects.
enum ObjectColorSource,values: ColorFromLayer (0),ColorFromMaterial (2),ColorFromObject (1),ColorFromParent (3)
"""
def __eq__(self, *args):
... | class ObjectColorSource(Enum, IComparable, IFormattable, IConvertible):
| """
Defines enumerated values for the source of display color of single objects.
enum ObjectColorSource,values: ColorFromLayer (0),ColorFromMaterial (2),ColorFromObject (1),ColorFromParent (3)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x=... | class ObjectColorSource(Enum, IComparable, IFormattable, IConvertible):
| 17 | 103 | 344 | 17 | 0 | YKato521/ironpython-stubs | release/stubs.min/Rhino/DocObjects/__init___parts/ObjectColorSource.py | Python | ObjectColorSource | ObjectColorSource | 1 | 47 | 1 | 1 | 4da23963d01f84d322abd88ea027bcd268b09c38 | bigcode/the-stack | train |
78dc733d050e58a30b0b6c11 | train | function | def _lint_image_name(path: Path, spec: str, errors: List[LintError]) -> None:
from materialize.mzcompose.services import (
DEFAULT_CONFLUENT_PLATFORM_VERSION,
LINT_DEBEZIUM_VERSIONS,
)
match = re.search(r"((?P<repo>[^/]+)/)?(?P<image>[^:]+)(:(?P<tag>.*))?", spec)
if not match:
e... | def _lint_image_name(path: Path, spec: str, errors: List[LintError]) -> None:
| from materialize.mzcompose.services import (
DEFAULT_CONFLUENT_PLATFORM_VERSION,
LINT_DEBEZIUM_VERSIONS,
)
match = re.search(r"((?P<repo>[^/]+)/)?(?P<image>[^:]+)(:(?P<tag>.*))?", spec)
if not match:
errors.append(LintError(path, f"malformatted image specification: {spec}"))
... | :
return
for (name, service) in composition["services"].items():
if service.get("mzbuild") == "materialized":
_lint_materialized_service(path, name, service, errors)
elif "mzbuild" not in service and "image" in service:
_lint_image_name(path, service["image"], errors... | 137 | 137 | 459 | 23 | 114 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | _lint_image_name | _lint_image_name | 102 | 150 | 102 | 102 | b672eb3e5c769cc4a6efae2d97aa51b55a727bc6 | bigcode/the-stack | train |
c32fa271a7a5d6265610e8ac | train | class | class UnknownCompositionError(UIError):
"""The specified composition was unknown."""
def __init__(self, name: str):
super().__init__(f"unknown composition {name!r}")
| class UnknownCompositionError(UIError):
| """The specified composition was unknown."""
def __init__(self, name: str):
super().__init__(f"unknown composition {name!r}")
| ,
)
import pg8000
import sqlparse
import yaml
from pg8000 import Cursor
from materialize import mzbuild, spawn, ui
from materialize.ui import UIError
T = TypeVar("T")
say = ui.speaker("C> ")
class UnknownCompositionError(UIError):
| 63 | 64 | 40 | 7 | 56 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | UnknownCompositionError | UnknownCompositionError | 65 | 69 | 65 | 65 | eeff393b81775bddbc472bee506d9b2ecc7e0b0f | bigcode/the-stack | train |
3e9efd94d4004203d0605580 | train | function | def _lint_composition(path: Path, composition: Any, errors: List[LintError]) -> None:
if "services" not in composition:
return
for (name, service) in composition["services"].items():
if service.get("mzbuild") == "materialized":
_lint_materialized_service(path, name, service, errors)... | def _lint_composition(path: Path, composition: Any, errors: List[LintError]) -> None:
| if "services" not in composition:
return
for (name, service) in composition["services"].items():
if service.get("mzbuild") == "materialized":
_lint_materialized_service(path, name, service, errors)
elif "mzbuild" not in service and "image" in service:
_lint_image... | (self.file)}: {self.message}"
def __lt__(self, other: "LintError") -> bool:
return (self.file, self.message) < (other.file, other.message)
def _lint_composition(path: Path, composition: Any, errors: List[LintError]) -> None:
| 64 | 64 | 145 | 23 | 41 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | _lint_composition | _lint_composition | 84 | 99 | 84 | 84 | 361316914a03d5c7aaa5d3313fbddbced021ef51 | bigcode/the-stack | train |
f6142daceb3d9d15f66fdcae | train | function | def _check_tcp(
cmd: List[str], host: str, port: int, timeout_secs: int, kind: str = ""
) -> List[str]:
cmd.extend(
[
"timeout",
str(timeout_secs),
"bash",
"-c",
f"cat < /dev/null > /dev/tcp/{host}/{port}",
]
)
try:
spaw... | def _check_tcp(
cmd: List[str], host: str, port: int, timeout_secs: int, kind: str = ""
) -> List[str]:
| cmd.extend(
[
"timeout",
str(timeout_secs),
"bash",
"-c",
f"cat < /dev/null > /dev/tcp/{host}/{port}",
]
)
try:
spawn.capture(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
ui.log_in_au... | :
args = self.args
return super().parse_known_args(args, namespace)
# TODO(benesch): replace with Docker health checks.
def _check_tcp(
cmd: List[str], host: str, port: int, timeout_secs: int, kind: str = ""
) -> List[str]:
| 64 | 64 | 168 | 34 | 30 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | _check_tcp | _check_tcp | 875 | 896 | 875 | 877 | 03c437de940bb314f75ee1411c735e75acdd22c4 | bigcode/the-stack | train |
8d78dfa8d7d33019ab256b75 | train | class | class WorkflowArgumentParser(argparse.ArgumentParser):
"""An argument parser provided to a workflow in a `Composition`.
You can call `add_argument` and other methods on this argument parser like
usual. When you are ready to parse arguments, call `parse_args` or
`parse_known_args` like usual; the argume... | class WorkflowArgumentParser(argparse.ArgumentParser):
| """An argument parser provided to a workflow in a `Composition`.
You can call `add_argument` and other methods on this argument parser like
usual. When you are ready to parse arguments, call `parse_args` or
`parse_known_args` like usual; the argument parser will automatically use
the arguments that... | `.
Attributes:
name: The name of the service.
config: The definition of the service.
"""
def __init__(self, name: str, config: ServiceConfig) -> None:
self.name = name
self.config = config
class WorkflowArgumentParser(argparse.ArgumentParser):
| 64 | 64 | 197 | 9 | 54 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | WorkflowArgumentParser | WorkflowArgumentParser | 851 | 871 | 851 | 851 | 7bb141f270700236be08b7a26ab3bcba95d1033f | bigcode/the-stack | train |
626044587428feffff1a99d9 | train | class | class Service:
"""A Docker Compose service in a `Composition`.
Attributes:
name: The name of the service.
config: The definition of the service.
"""
def __init__(self, name: str, config: ServiceConfig) -> None:
self.name = name
self.config = config
| class Service:
| """A Docker Compose service in a `Composition`.
Attributes:
name: The name of the service.
config: The definition of the service.
"""
def __init__(self, name: str, config: ServiceConfig) -> None:
self.name = name
self.config = config
| to join.
TODO(benesch): this should use a nested TypedDict.
"""
deploy: Dict[str, Dict[str, Dict[str, str]]]
"""Additional deployment configuration, like resource limits.
TODO(benesch): this should use a nested TypedDict.
"""
class Service:
| 63 | 64 | 68 | 3 | 60 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | Service | Service | 838 | 848 | 838 | 838 | e68186879cb903eb6e94876a26c785a281bd23e2 | bigcode/the-stack | train |
ad6d47e3bcb44f2020923a90 | train | class | class ServiceConfig(TypedDict, total=False):
"""The definition of a service in Docker Compose.
This object corresponds directly to the YAML definition in a
docker-compose.yml file, plus two mzcompose-specific attributes. Full
details are available in [Services top-level element][ref] chapter of the
... | class ServiceConfig(TypedDict, total=False):
| """The definition of a service in Docker Compose.
This object corresponds directly to the YAML definition in a
docker-compose.yml file, plus two mzcompose-specific attributes. Full
details are available in [Services top-level element][ref] chapter of the
Compose Specification.
[ref]: https://g... | name: str = "materialize",
host: str = "localhost",
port: Optional[int] = None,
timeout_secs: int = 60,
query: str = "SELECT 1",
expected: Union[Iterable[Any], Literal["any"]] = [[1]],
print_result: bool = False,
) -> None:
"""Like `Workflow.wait_for_postgres`... | 156 | 156 | 520 | 10 | 146 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | ServiceConfig | ServiceConfig | 762 | 835 | 762 | 762 | e386242e169edb732a89fdae6fa884b2a02f7ef8 | bigcode/the-stack | train |
eb97dfb210fab988a63bec2b | train | function | def _wait_for_pg(
timeout_secs: int,
query: str,
dbname: str,
port: int,
host: str,
user: str,
password: str,
print_result: bool,
expected: Union[Iterable[Any], Literal["any"]],
) -> None:
"""Wait for a pg-compatible database (includes materialized)"""
args = f"dbname={dbname... | def _wait_for_pg(
timeout_secs: int,
query: str,
dbname: str,
port: int,
host: str,
user: str,
password: str,
print_result: bool,
expected: Union[Iterable[Any], Literal["any"]],
) -> None:
| """Wait for a pg-compatible database (includes materialized)"""
args = f"dbname={dbname} host={host} port={port} user={user} password={password}"
ui.progress(f"waiting for {args} to handle {query!r}", "C")
error = None
for remaining in ui.timeout_loop(timeout_secs):
try:
conn = p... | {}".format(
kind, host, port, ui.shell_quote(cmd), e, e.stdout, e.stderr
)
)
raise
return cmd
# TODO(benesch): replace with Docker health checks.
def _wait_for_pg(
timeout_secs: int,
query: str,
dbname: str,
port: int,
host: str,
user: str,
p... | 111 | 111 | 370 | 65 | 46 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | _wait_for_pg | _wait_for_pg | 900 | 947 | 900 | 910 | 65dc05f4bfd31bd91154b55a7cbbe63a6a632121 | bigcode/the-stack | train |
717a68a0a86e260bba8f8d64 | train | class | class Composition:
"""A parsed mzcompose.yml with a loaded mzcompose.py file."""
@dataclass
class TestResult:
duration: float
error: Optional[str]
def __init__(
self,
repo: mzbuild.Repository,
name: str,
preserve_ports: bool = False,
silent: bool... | class Composition:
| """A parsed mzcompose.yml with a loaded mzcompose.py file."""
@dataclass
class TestResult:
duration: float
error: Optional[str]
def __init__(
self,
repo: mzbuild.Repository,
name: str,
preserve_ports: bool = False,
silent: bool = False,
):
... | spec} with official confluentinc/cp-zookeeper image"
)
)
if repo == "wurstmeister" and image == "kafka":
errors.append(
LintError(path, f"replace {spec} with official confluentinc/cp-kafka image")
)
def _lint_materialized_service(
path: Path, name: str, service... | 256 | 256 | 4,507 | 3 | 253 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | Composition | Composition | 178 | 759 | 178 | 178 | 1d4de83e92a34b97dcdd799fd35daee28eac180f | bigcode/the-stack | train |
06940e8fe28cca2e0354b16e | train | class | class LintError:
def __init__(self, file: Path, message: str):
self.file = file
self.message = message
def __str__(self) -> str:
return f"{os.path.relpath(self.file)}: {self.message}"
def __lt__(self, other: "LintError") -> bool:
return (self.file, self.message) < (other.fi... | class LintError:
| def __init__(self, file: Path, message: str):
self.file = file
self.message = message
def __str__(self) -> str:
return f"{os.path.relpath(self.file)}: {self.message}"
def __lt__(self, other: "LintError") -> bool:
return (self.file, self.message) < (other.file, other.message... |
T = TypeVar("T")
say = ui.speaker("C> ")
class UnknownCompositionError(UIError):
"""The specified composition was unknown."""
def __init__(self, name: str):
super().__init__(f"unknown composition {name!r}")
class LintError:
| 63 | 64 | 91 | 5 | 58 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | LintError | LintError | 72 | 81 | 72 | 72 | 0cb6f0378355d496033896190c612c99e842ce88 | bigcode/the-stack | train |
3a3e2ad5b78feaff5f96226a | train | function | def _lint_materialized_service(
path: Path, name: str, service: Any, errors: List[LintError]
) -> None:
# command may be a string that is passed to the shell, or a list of
# arguments.
command = service.get("command", "")
if isinstance(command, str):
command = command.split() # split on whi... | def _lint_materialized_service(
path: Path, name: str, service: Any, errors: List[LintError]
) -> None:
# command may be a string that is passed to the shell, or a list of
# arguments.
| command = service.get("command", "")
if isinstance(command, str):
command = command.split() # split on whitespace to extract individual arguments
if "--disable-telemetry" not in command:
errors.append(
LintError(
path,
"materialized service comman... | uentinc/cp-kafka image")
)
def _lint_materialized_service(
path: Path, name: str, service: Any, errors: List[LintError]
) -> None:
# command may be a string that is passed to the shell, or a list of
# arguments.
| 64 | 64 | 191 | 54 | 10 | lluki/materialize | misc/python/materialize/mzcompose/__init__.py | Python | _lint_materialized_service | _lint_materialized_service | 153 | 175 | 153 | 157 | bc3a70fed1a1f989dd569ac1b32b9ebdbca676fd | bigcode/the-stack | train |
f95cb6c8b8c732945c746033 | train | function | def haiss_m1(ts, style='boxcar', width=None, limit_range=(400.0,700.0)):
''' Wrapper function for Haiss method 1. Allows for range slicing/smoothing and applies
haiss_m1 over the entire timespectra object.
Parameters:
---------
ts: TimeSpectra.
style: Smoothing style. ... | def haiss_m1(ts, style='boxcar', width=None, limit_range=(400.0,700.0)):
| ''' Wrapper function for Haiss method 1. Allows for range slicing/smoothing and applies
haiss_m1 over the entire timespectra object.
Parameters:
---------
ts: TimeSpectra.
style: Smoothing style. For now, only boxcar is used.
width: Smoothing binwidth in units ... | car smoothing is available')
### Slice data
if limit_range:
if len(limit_range) != 2:
raise AttributeError('Limit_range must be a length-2 iterable.')
ts=ts.ix[ limit_range[0]:limit_range[1] ]
return ts
def haiss_m1(ts, style='boxcar', width=Non... | 93 | 93 | 313 | 26 | 66 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | haiss_m1 | haiss_m1 | 63 | 93 | 63 | 63 | 935acc939978e8f010a8a5615227837d5cd7d13e | bigcode/the-stack | train |
30302dc2e457be8803968936 | train | function | def haiss_m3(ts, Cau, dilution=None, style='boxcar', width=None, limit_range=(400.0,700.0), peak_width=None, exp=True):
''' Wrapper function for Haiss method 3. Estimates diamter of gold nanoparticles
based on the SPR max of the absorbance and the initial concentration of gold use to synthesize
th... | def haiss_m3(ts, Cau, dilution=None, style='boxcar', width=None, limit_range=(400.0,700.0), peak_width=None, exp=True):
| ''' Wrapper function for Haiss method 3. Estimates diamter of gold nanoparticles
based on the SPR max of the absorbance and the initial concentration of gold use to synthesize
the nanoparticles. Should be valid between 5-50nm diatmeters. Please take note of the dilution
parameter descrip... | Haiss fit parameters are used.
Otherwise, theoretical Haiss fit parameters are used.
Notes:
-----------
the diameter is calcualted by dividing the absorbance at the spr
maximum by that at 450nm and fitting to experimental/theoretical
parameters.
''... | 201 | 201 | 672 | 38 | 162 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | haiss_m3 | haiss_m3 | 213 | 268 | 213 | 213 | 1fcdca2b48c100a40e1bd1c8eda112004ac4c781 | bigcode/the-stack | train |
654d6141d614484ea50c3611 | train | function | def haiss_m2(ts, ref=450.0, width=None, style='boxcar', ref_width=None,
peak_width=None, limit_range=(400.0,700.0), exp=True):
''' Wrapper for haiss_m2 to return diamter of nanoparticles based on features of its
absorbance spectrum relative to water. Program has special call options to... | def haiss_m2(ts, ref=450.0, width=None, style='boxcar', ref_width=None,
peak_width=None, limit_range=(400.0,700.0), exp=True):
| ''' Wrapper for haiss_m2 to return diamter of nanoparticles based on features of its
absorbance spectrum relative to water. Program has special call options to handle
smoothing and range slicing on the fly.
Parameters:
----------
curve:
smooth: If True, applies smoothing to ts.
... | spec.core.utilities.
Code may error if user passes a curve with
a maximum very far from 510 (lam0 in haiss_m1) as the log will blowup.
'''
ts=_haiss_preformat(ts, style=style, width=width, limit_range=limit_range)
### Feed index at maxiumum. to haiss function
spr... | 144 | 145 | 485 | 45 | 99 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | haiss_m2 | haiss_m2 | 96 | 130 | 96 | 97 | 4758cbe38034823dec837f5890147296c13e7ab0 | bigcode/the-stack | train |
43d1bd1d61886a10c87a46bf | train | function | def haiss_conc(ts, d, style='boxcar', width=None, limit_range=(400.0,700.0), ref=450.0, ref_width=None, exp=True):
''' Return estimation of AuNP concentration given the diameter of gold nanoparticles as the Absorbance
at 450nm (or other wavelength controlled by ref). Should be valid for particles with diam... | def haiss_conc(ts, d, style='boxcar', width=None, limit_range=(400.0,700.0), ref=450.0, ref_width=None, exp=True):
| ''' Return estimation of AuNP concentration given the diameter of gold nanoparticles as the Absorbance
at 450nm (or other wavelength controlled by ref). Should be valid for particles with diameters ranging
from 2.5nm to 100nm and possibly beyond these limits. Works for stock and dilute samples.
... | .89*10**-6
### Calculate diameter from experimental fit parameters
if exp:
C1=-4.75
C2=0.314
### Calculate diameter from theoretical fit parameters
else:
C1=-4.70
C2=0.300
return ( (Aspr * term )/ (Cau * math.exp(C1) ) )**(1.0/C2)
def haiss_conc(ts, d, style='box... | 135 | 135 | 453 | 41 | 94 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | haiss_conc | haiss_conc | 288 | 319 | 288 | 288 | 075b2748c5e7b7a28d440fc9aa7a75f540b4c951 | bigcode/the-stack | train |
0450358d4b4657803662b520 | train | function | def _haiss_m1(lambda_spr):
''' Return diameter from wavelength at spr maximum of absorbance curve.
Parameters:
-----------
lambda_spr: the wavelength at spr absorbance maximum.
Notes:
-----------
this method is not accurate for particles with diameter less than 25nm.
'''
lambda_0=... | def _haiss_m1(lambda_spr):
| ''' Return diameter from wavelength at spr maximum of absorbance curve.
Parameters:
-----------
lambda_spr: the wavelength at spr absorbance maximum.
Notes:
-----------
this method is not accurate for particles with diameter less than 25nm.
'''
lambda_0=512
L1=6.53
L2=0.02... | ST WAVELENGTH
if Aspr==0.0 or Aref==0.0:
d=np.NaN
else:
d= _haiss_m2(Aspr, Aref, exp=exp)
return d
def _haiss_m1(lambda_spr):
| 64 | 64 | 115 | 10 | 53 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | _haiss_m1 | _haiss_m1 | 162 | 179 | 162 | 162 | 66d495355ea9af92df918c2a8be61cc29546648a | bigcode/the-stack | train |
8535115bd50c096b5bb16149 | train | function | def _haiss_m2(Aspr, A450, exp=True):
''' Return diameter from absorbance at spr and 450 from Haiss et al.
Parameters:
-----------
Aspr: the absorbance at spr max.
A450: the absorbance at 450nm.
exp: If true, experimentally derived Haiss fit parameters are used.
... | def _haiss_m2(Aspr, A450, exp=True):
| ''' Return diameter from absorbance at spr and 450 from Haiss et al.
Parameters:
-----------
Aspr: the absorbance at spr max.
A450: the absorbance at 450nm.
exp: If true, experimentally derived Haiss fit parameters are used.
Otherwise, theoretical Haiss... | 25nm.
'''
lambda_0=512
L1=6.53
L2=0.0216
d=(math.log((lambda_spr-lambda_0)/L1))/L2
return d
def _haiss_m2(Aspr, A450, exp=True):
| 70 | 70 | 235 | 16 | 53 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | _haiss_m2 | _haiss_m2 | 182 | 211 | 182 | 182 | f82dca1c2a14bc01ff86e43797c4d4371e370b4a | bigcode/the-stack | train |
c07763c42b9ed3d641093bda | train | function | def _m2_haiss(curve, ref=450.0, peak_width=None, ref_width=None, exp=True):
''' Private method to quick_haiss_m2. This separation is necessary to allow
haissm2 (with 2 required arguments) to be compatable with quick_haiss_m2.
In other words, because we need to compute Aspr and Aref separately, can'... | def _m2_haiss(curve, ref=450.0, peak_width=None, ref_width=None, exp=True):
| ''' Private method to quick_haiss_m2. This separation is necessary to allow
haissm2 (with 2 required arguments) to be compatable with quick_haiss_m2.
In other words, because we need to compute Aspr and Aref separately, can't
just call .apply() method in the normal fashion as done for exampl... | the log will blowup.
'''
ts=_haiss_preformat(ts, style=style, width=width, limit_range=limit_range)
return ts.apply(_m2_haiss, ref=ref, peak_width=peak_width, ref_width=ref_width, exp=exp)
def _m2_haiss(curve, ref=450.0, peak_width=None, ref_width=None, exp=True):
| 91 | 91 | 304 | 27 | 64 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | _m2_haiss | _m2_haiss | 133 | 160 | 133 | 133 | 001f8d2057f5e743e5b146da3daf1c67fa697c91 | bigcode/the-stack | train |
df7690595291d32bfe0ae51f | train | function | def _haiss_preformat(ts, style='boxcar', width=None, limit_range=(400.0,700.0)):
'''Called by other haiss method to preforma the timespectra before calling
haiss functions.
See description under haiss_m1 for explanation of parameters. '''
### Ensure ts is in units of absorbance and has... | def _haiss_preformat(ts, style='boxcar', width=None, limit_range=(400.0,700.0)):
| '''Called by other haiss method to preforma the timespectra before calling
haiss functions.
See description under haiss_m1 for explanation of parameters. '''
### Ensure ts is in units of absorbance and has nanometer spectral unit
if ts.iunit != 'a':
try:
ts.iuni... | Haiss, Thanh, Aveyard, Fernig, Determination of Size and Concentration of Gold
Nanoparticles from UV-Vis Spectra Anal. Chem, 79, 2007.
Three functions are build based on the results of this paper, as well as a utility
for estimating nanoparticle concentration.'''
import math
import numpy as np
import wa... | 108 | 108 | 362 | 27 | 80 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | _haiss_preformat | _haiss_preformat | 14 | 61 | 14 | 14 | e483bdfe79712c412cce71795f694d58b1e1c186 | bigcode/the-stack | train |
fe4448b632a1575fce5e0cd0 | train | function | def _haiss_conc(Aref, d):
''' See haiss conc '''
num=Aref * 10**14
t1=1.36 * math.exp(-( (d-96.8)/(78.2))**2 )
den=d**2 * (-0.295+ t1)
return num/den
| def _haiss_conc(Aref, d):
| ''' See haiss conc '''
num=Aref * 10**14
t1=1.36 * math.exp(-( (d-96.8)/(78.2))**2 )
den=d**2 * (-0.295+ t1)
return num/den
| -ref_width : ref+ref_width] #Stil slices by wavelength
else:
Aref=ts.ix[ref] #FIND CLOSEST WAVELENGTH
return Aref.apply(_haiss_conc, d=d)
def _haiss_conc(Aref, d):
| 64 | 64 | 73 | 11 | 53 | hugadams/scikit-spectra | skspec/nptools/haiss.py | Python | _haiss_conc | _haiss_conc | 322 | 327 | 322 | 322 | 2cb9d91231a393dc5cea890cc0149d5e295d99c3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.