hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2
xdsoar/pocket-archive-stream
archiver/util.py
[ "MIT" ]
Python
cleanup_archive
<not_specific>
def cleanup_archive(archive_path, links): """move any incorrectly named folders to their canonical locations""" # for each folder that exists, see if we can match it up with a known good link # if we can, then merge the two folders (TODO: if not, move it to lost & found) unmatched = [] bad_fol...
move any incorrectly named folders to their canonical locations
move any incorrectly named folders to their canonical locations
[ "move", "any", "incorrectly", "named", "folders", "to", "their", "canonical", "locations" ]
def cleanup_archive(archive_path, links): unmatched = [] bad_folders = [] if not os.path.exists(archive_path): return for folder in os.listdir(archive_path): try: files = os.listdir(os.path.join(archive_path, folder)) except NotADirectoryError: continue ...
[ "def", "cleanup_archive", "(", "archive_path", ",", "links", ")", ":", "unmatched", "=", "[", "]", "bad_folders", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "archive_path", ")", ":", "return", "for", "folder", "in", "os", ".", ...
move any incorrectly named folders to their canonical locations
[ "move", "any", "incorrectly", "named", "folders", "to", "their", "canonical", "locations" ]
[ "\"\"\"move any incorrectly named folders to their canonical locations\"\"\"", "# for each folder that exists, see if we can match it up with a known good link", "# if we can, then merge the two folders (TODO: if not, move it to lost & found)", "# delete empty folders" ]
[ { "param": "archive_path", "type": null }, { "param": "links", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "archive_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "links", "type": null, "docstring": null, "docstring_t...
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2
xdsoar/pocket-archive-stream
archiver/util.py
[ "MIT" ]
Python
wget_output_path
<not_specific>
def wget_output_path(link, look_in=None): """calculate the path to the wgetted .html file, since wget may adjust some paths to be different than the base_url path. See docs on wget --adjust-extension (-E) """ # if we have it stored, always prefer the actual output path to computed one if link....
calculate the path to the wgetted .html file, since wget may adjust some paths to be different than the base_url path. See docs on wget --adjust-extension (-E)
calculate the path to the wgetted .html file, since wget may adjust some paths to be different than the base_url path. See docs on wget --adjust-extension (-E)
[ "calculate", "the", "path", "to", "the", "wgetted", ".", "html", "file", "since", "wget", "may", "adjust", "some", "paths", "to", "be", "different", "than", "the", "base_url", "path", ".", "See", "docs", "on", "wget", "--", "adjust", "-", "extension", "(...
def wget_output_path(link, look_in=None): if link.get('latest', {}).get('wget'): return link['latest']['wget'] urlencode = lambda s: quote(s, encoding='utf-8', errors='replace') if link['type'] in ('PDF', 'image'): return urlencode(link['base_url']) wget_folder = link['base_url'].rsplit(...
[ "def", "wget_output_path", "(", "link", ",", "look_in", "=", "None", ")", ":", "if", "link", ".", "get", "(", "'latest'", ",", "{", "}", ")", ".", "get", "(", "'wget'", ")", ":", "return", "link", "[", "'latest'", "]", "[", "'wget'", "]", "urlencod...
calculate the path to the wgetted .html file, since wget may adjust some paths to be different than the base_url path.
[ "calculate", "the", "path", "to", "the", "wgetted", ".", "html", "file", "since", "wget", "may", "adjust", "some", "paths", "to", "be", "different", "than", "the", "base_url", "path", "." ]
[ "\"\"\"calculate the path to the wgetted .html file, since wget may\n adjust some paths to be different than the base_url path.\n\n See docs on wget --adjust-extension (-E)\n \"\"\"", "# if we have it stored, always prefer the actual output path to computed one", "# Since the wget algorithm to for -E (...
[ { "param": "link", "type": null }, { "param": "look_in", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "link", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "look_in", "type": null, "docstring": null, "docstring_tokens"...
14f8ccff14cbff40f09e7cf7f7fd25cc36e1c4b2
xdsoar/pocket-archive-stream
archiver/util.py
[ "MIT" ]
Python
derived_link_info
<not_specific>
def derived_link_info(link): """extend link info with the archive urls and other derived data""" link_info = { **link, 'date': datetime.fromtimestamp(float(link['timestamp'])).strftime('%Y-%m-%d %H:%M'), 'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(*...
extend link info with the archive urls and other derived data
extend link info with the archive urls and other derived data
[ "extend", "link", "info", "with", "the", "archive", "urls", "and", "other", "derived", "data" ]
def derived_link_info(link): link_info = { **link, 'date': datetime.fromtimestamp(float(link['timestamp'])).strftime('%Y-%m-%d %H:%M'), 'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(**link), 'favicon_url': 'archive/{timestamp}/favicon.ico'.format(*...
[ "def", "derived_link_info", "(", "link", ")", ":", "link_info", "=", "{", "**", "link", ",", "'date'", ":", "datetime", ".", "fromtimestamp", "(", "float", "(", "link", "[", "'timestamp'", "]", ")", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M'", ")", ","...
extend link info with the archive urls and other derived data
[ "extend", "link", "info", "with", "the", "archive", "urls", "and", "other", "derived", "data" ]
[ "\"\"\"extend link info with the archive urls and other derived data\"\"\"", "# PDF and images are handled slightly differently", "# wget, screenshot, & pdf urls all point to the same file" ]
[ { "param": "link", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "link", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2b9e820daac7680675bfc8fdb0cd106a064b2444
hmpf/social-core
social_core/backends/microsoft.py
[ "BSD-3-Clause" ]
Python
user_data
<not_specific>
def user_data(self, access_token, *args, **kwargs): """Return user data by querying Microsoft service""" return self.get_json( 'https://graph.microsoft.com/v1.0/me', headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'applicat...
Return user data by querying Microsoft service
Return user data by querying Microsoft service
[ "Return", "user", "data", "by", "querying", "Microsoft", "service" ]
def user_data(self, access_token, *args, **kwargs): return self.get_json( 'https://graph.microsoft.com/v1.0/me', headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Bearer ' + acces...
[ "def", "user_data", "(", "self", ",", "access_token", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "self", ".", "get_json", "(", "'https://graph.microsoft.com/v1.0/me'", ",", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlenc...
Return user data by querying Microsoft service
[ "Return", "user", "data", "by", "querying", "Microsoft", "service" ]
[ "\"\"\"Return user data by querying Microsoft service\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "access_token", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "access_token", "type": null, "docstring": null, "docstring_to...
0dae254bd3b5ea71633e5f5ddc78fc84f47a4aac
lk-geimfari/mimesis
mimesis/schema.py
[ "MIT" ]
Python
perform
Any
def perform( self, name: Optional[str] = None, key: Optional[Callable[[Any], Any]] = None, **kwargs: Any ) -> Any: """Performs the value of the field by its name. It takes any string which represents the name of any method of any supported data provider and t...
Performs the value of the field by its name. It takes any string which represents the name of any method of any supported data provider and the ``**kwargs`` of this method. .. note:: Some data providers have methods with the same names and in such cases, you can explicitly define t...
Performs the value of the field by its name. It takes any string which represents the name of any method of any supported data provider and the ``**kwargs`` of this method.
[ "Performs", "the", "value", "of", "the", "field", "by", "its", "name", ".", "It", "takes", "any", "string", "which", "represents", "the", "name", "of", "any", "method", "of", "any", "supported", "data", "provider", "and", "the", "`", "`", "**", "kwargs",...
def perform( self, name: Optional[str] = None, key: Optional[Callable[[Any], Any]] = None, **kwargs: Any ) -> Any: if name is None: raise FieldError() def tail_parser(tails: str, obj: Any) -> Any: provider_name, method_name = tails.split(".", 1...
[ "def", "perform", "(", "self", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", "key", ":", "Optional", "[", "Callable", "[", "[", "Any", "]", ",", "Any", "]", "]", "=", "None", ",", "**", "kwargs", ":", "Any", ")", "->", "Any",...
Performs the value of the field by its name.
[ "Performs", "the", "value", "of", "the", "field", "by", "its", "name", "." ]
[ "\"\"\"Performs the value of the field by its name.\n\n It takes any string which represents the name of any method of\n any supported data provider and the ``**kwargs`` of this method.\n\n .. note:: Some data providers have methods with the same names\n and in such cases, you can ex...
[ { "param": "self", "type": null }, { "param": "name", "type": "Optional[str]" }, { "param": "key", "type": "Optional[Callable[[Any], Any]]" }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [ { "docstring": "Value which represented by method.", "docstring_tokens": [ "Value", "which", "represented", "by", "method", "." ], "type": null } ], "raises": [ { "docstring": "if provider not\nsupported or if...
0dae254bd3b5ea71633e5f5ddc78fc84f47a4aac
lk-geimfari/mimesis
mimesis/schema.py
[ "MIT" ]
Python
tail_parser
Any
def tail_parser(tails: str, obj: Any) -> Any: """Return method from end of tail. :param tails: Tail string :param obj: Search tail from this object :return last tailed method """ provider_name, method_name = tails.split(".", 1) if "."...
Return method from end of tail. :param tails: Tail string :param obj: Search tail from this object :return last tailed method
Return method from end of tail.
[ "Return", "method", "from", "end", "of", "tail", "." ]
def tail_parser(tails: str, obj: Any) -> Any: provider_name, method_name = tails.split(".", 1) if "." in method_name: raise FieldError(name) attr = getattr(obj, provider_name) if attr is not None: try: return getattr(att...
[ "def", "tail_parser", "(", "tails", ":", "str", ",", "obj", ":", "Any", ")", "->", "Any", ":", "provider_name", ",", "method_name", "=", "tails", ".", "split", "(", "\".\"", ",", "1", ")", "if", "\".\"", "in", "method_name", ":", "raise", "FieldError",...
Return method from end of tail.
[ "Return", "method", "from", "end", "of", "tail", "." ]
[ "\"\"\"Return method from end of tail.\n\n :param tails: Tail string\n :param obj: Search tail from this object\n :return last tailed method\n \"\"\"" ]
[ { "param": "tails", "type": "str" }, { "param": "obj", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tails", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": "Any", "docstring": null, "docstring_tokens":...
0dae254bd3b5ea71633e5f5ddc78fc84f47a4aac
lk-geimfari/mimesis
mimesis/schema.py
[ "MIT" ]
Python
create
List[JSON]
def create(self, iterations: int = 1) -> List[JSON]: """Creates a list of a fulfilled schemas. .. note:: This method evaluates immediately, so be careful on creating large datasets otherwise you're risking running out of memory. If you need a lazy version of this me...
Creates a list of a fulfilled schemas. .. note:: This method evaluates immediately, so be careful on creating large datasets otherwise you're risking running out of memory. If you need a lazy version of this method, see :meth:`iterator` :param iteration...
Creates a list of a fulfilled schemas. note:: This method evaluates immediately, so be careful on creating large datasets otherwise you're risking running out of memory. If you need a lazy version of this method, see :meth:`iterator`
[ "Creates", "a", "list", "of", "a", "fulfilled", "schemas", ".", "note", "::", "This", "method", "evaluates", "immediately", "so", "be", "careful", "on", "creating", "large", "datasets", "otherwise", "you", "'", "re", "risking", "running", "out", "of", "memor...
def create(self, iterations: int = 1) -> List[JSON]: if iterations < self._MIN_ITERATIONS_VALUE: raise ValueError("The number of iterations must be greater than 0.") return [self._schema() for _ in range(iterations)]
[ "def", "create", "(", "self", ",", "iterations", ":", "int", "=", "1", ")", "->", "List", "[", "JSON", "]", ":", "if", "iterations", "<", "self", ".", "_MIN_ITERATIONS_VALUE", ":", "raise", "ValueError", "(", "\"The number of iterations must be greater than 0.\"...
Creates a list of a fulfilled schemas.
[ "Creates", "a", "list", "of", "a", "fulfilled", "schemas", "." ]
[ "\"\"\"Creates a list of a fulfilled schemas.\n\n .. note::\n This method evaluates immediately, so be careful on creating\n large datasets otherwise you're risking running out of memory.\n\n If you need a lazy version of this method, see\n :meth:`iterator`\n\n ...
[ { "param": "self", "type": null }, { "param": "iterations", "type": "int" } ]
{ "returns": [ { "docstring": "List of fulfilled schemas.", "docstring_tokens": [ "List", "of", "fulfilled", "schemas", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstrin...
0dae254bd3b5ea71633e5f5ddc78fc84f47a4aac
lk-geimfari/mimesis
mimesis/schema.py
[ "MIT" ]
Python
iterator
Iterator[JSON]
def iterator(self, iterations: int = 1) -> Iterator[JSON]: """Fulfills schema in a lazy way. :param iterations: Number of iterations. :return: List of fulfilled schemas. """ if iterations < self._MIN_ITERATIONS_VALUE: raise ValueError("The number of iterations must ...
Fulfills schema in a lazy way. :param iterations: Number of iterations. :return: List of fulfilled schemas.
Fulfills schema in a lazy way.
[ "Fulfills", "schema", "in", "a", "lazy", "way", "." ]
def iterator(self, iterations: int = 1) -> Iterator[JSON]: if iterations < self._MIN_ITERATIONS_VALUE: raise ValueError("The number of iterations must be greater than 0.") for item in range(iterations): yield self._schema()
[ "def", "iterator", "(", "self", ",", "iterations", ":", "int", "=", "1", ")", "->", "Iterator", "[", "JSON", "]", ":", "if", "iterations", "<", "self", ".", "_MIN_ITERATIONS_VALUE", ":", "raise", "ValueError", "(", "\"The number of iterations must be greater tha...
Fulfills schema in a lazy way.
[ "Fulfills", "schema", "in", "a", "lazy", "way", "." ]
[ "\"\"\"Fulfills schema in a lazy way.\n\n :param iterations: Number of iterations.\n :return: List of fulfilled schemas.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "iterations", "type": "int" } ]
{ "returns": [ { "docstring": "List of fulfilled schemas.", "docstring_tokens": [ "List", "of", "fulfilled", "schemas", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstrin...
6c1e06ab3c04cf4716fdb354b8206aefe59f566e
yifeim/recurrent-intensity-model-experiments
src/rime/models/transformer.py
[ "Apache-2.0" ]
Python
forward
<not_specific>
def forward(self, batch): """ output user embedding at lengths-1 positions """ TN_inp, lengths = batch mask = self.model._generate_square_subsequent_mask(len(TN_inp)).to(TN_inp.device) TNC_enc = self.model.encoder(TN_inp) * np.sqrt(self.model.ninp) TNC_enc = self.model.pos_encod...
output user embedding at lengths-1 positions
output user embedding at lengths-1 positions
[ "output", "user", "embedding", "at", "lengths", "-", "1", "positions" ]
def forward(self, batch): TN_inp, lengths = batch mask = self.model._generate_square_subsequent_mask(len(TN_inp)).to(TN_inp.device) TNC_enc = self.model.encoder(TN_inp) * np.sqrt(self.model.ninp) TNC_enc = self.model.pos_encoder(TNC_enc) TNC_out = self.model.transformer_encoder(T...
[ "def", "forward", "(", "self", ",", "batch", ")", ":", "TN_inp", ",", "lengths", "=", "batch", "mask", "=", "self", ".", "model", ".", "_generate_square_subsequent_mask", "(", "len", "(", "TN_inp", ")", ")", ".", "to", "(", "TN_inp", ".", "device", ")"...
output user embedding at lengths-1 positions
[ "output", "user", "embedding", "at", "lengths", "-", "1", "positions" ]
[ "\"\"\" output user embedding at lengths-1 positions \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "batch", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "batch", "type": null, "docstring": null, "docstring_tokens": ...
74faf5416897ee0fbc04653f913dc608c4c32eb5
yifeim/recurrent-intensity-model-experiments
src/rime/dataset/__init__.py
[ "Apache-2.0" ]
Python
prepare_minimal_dataset
<not_specific>
def prepare_minimal_dataset(): """ minimal dataset to enable main workflow in unit tests """ event_df = pd.DataFrame([ ["u1", "i1", 3], ["u2", "i2", 5], ["u3", "i3", 7], ["u3", "i4", 9], ], columns=["USER_ID", "ITEM_ID", "TIMESTAMP"]) user_df = pd.Series({ "u1": ...
minimal dataset to enable main workflow in unit tests
minimal dataset to enable main workflow in unit tests
[ "minimal", "dataset", "to", "enable", "main", "workflow", "in", "unit", "tests" ]
def prepare_minimal_dataset(): event_df = pd.DataFrame([ ["u1", "i1", 3], ["u2", "i2", 5], ["u3", "i3", 7], ["u3", "i4", 9], ], columns=["USER_ID", "ITEM_ID", "TIMESTAMP"]) user_df = pd.Series({ "u1": 4, "u2": float("inf"), "u3": 9, }).to_frame("...
[ "def", "prepare_minimal_dataset", "(", ")", ":", "event_df", "=", "pd", ".", "DataFrame", "(", "[", "[", "\"u1\"", ",", "\"i1\"", ",", "3", "]", ",", "[", "\"u2\"", ",", "\"i2\"", ",", "5", "]", ",", "[", "\"u3\"", ",", "\"i3\"", ",", "7", "]", "...
minimal dataset to enable main workflow in unit tests
[ "minimal", "dataset", "to", "enable", "main", "workflow", "in", "unit", "tests" ]
[ "\"\"\" minimal dataset to enable main workflow in unit tests \"\"\"", "# +inf=training-only user, unless added after create_dataset", "# mark and trim _holdout by [TEST_START_TIME, TEST_START_TIME + horizon)", "# can be customized by setting _holdout as 0=training and 1=testing.", "# add _hist_items, _hist...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
74faf5416897ee0fbc04653f913dc608c4c32eb5
yifeim/recurrent-intensity-model-experiments
src/rime/dataset/__init__.py
[ "Apache-2.0" ]
Python
prepare_synthetic_data
<not_specific>
def prepare_synthetic_data(split_fn_name, exclude_train=False, num_users=300, num_items=200, num_events=10000): """ prepare synthetic data for end-to-end unit tests """ event_df = pd.DataFrame({ 'USER_ID': np.random.choice(num_users, num_events), 'ITEM_ID': np.random.c...
prepare synthetic data for end-to-end unit tests
prepare synthetic data for end-to-end unit tests
[ "prepare", "synthetic", "data", "for", "end", "-", "to", "-", "end", "unit", "tests" ]
def prepare_synthetic_data(split_fn_name, exclude_train=False, num_users=300, num_items=200, num_events=10000): event_df = pd.DataFrame({ 'USER_ID': np.random.choice(num_users, num_events), 'ITEM_ID': np.random.choice(num_items, num_events), 'TIMESTAMP': np.random....
[ "def", "prepare_synthetic_data", "(", "split_fn_name", ",", "exclude_train", "=", "False", ",", "num_users", "=", "300", ",", "num_items", "=", "200", ",", "num_events", "=", "10000", ")", ":", "event_df", "=", "pd", ".", "DataFrame", "(", "{", "'USER_ID'", ...
prepare synthetic data for end-to-end unit tests
[ "prepare", "synthetic", "data", "for", "end", "-", "to", "-", "end", "unit", "tests" ]
[ "\"\"\" prepare synthetic data for end-to-end unit tests \"\"\"", "# for hawkes_poisson verification purposes" ]
[ { "param": "split_fn_name", "type": null }, { "param": "exclude_train", "type": null }, { "param": "num_users", "type": null }, { "param": "num_items", "type": null }, { "param": "num_events", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "split_fn_name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "exclude_train", "type": null, "docstring": null, "do...
abe26958521a864f68dce326487ed0c393199497
yifeim/recurrent-intensity-model-experiments
src/rime/metrics/__init__.py
[ "Apache-2.0" ]
Python
evaluate_assigned
<not_specific>
def evaluate_assigned(target_csr, assigned_csr, score_mat=None, axis=None, min_total_recs=0, device="cpu"): """ compare targets and recommendation assignments on user-item matrix """ hit = _multiply(target_csr, assigned_csr) min_total_recs = max(min_total_recs, assigned_csr.sum()) ...
compare targets and recommendation assignments on user-item matrix
compare targets and recommendation assignments on user-item matrix
[ "compare", "targets", "and", "recommendation", "assignments", "on", "user", "-", "item", "matrix" ]
def evaluate_assigned(target_csr, assigned_csr, score_mat=None, axis=None, min_total_recs=0, device="cpu"): hit = _multiply(target_csr, assigned_csr) min_total_recs = max(min_total_recs, assigned_csr.sum()) out = { 'prec': hit.sum() / min_total_recs, 'recs/user': assign...
[ "def", "evaluate_assigned", "(", "target_csr", ",", "assigned_csr", ",", "score_mat", "=", "None", ",", "axis", "=", "None", ",", "min_total_recs", "=", "0", ",", "device", "=", "\"cpu\"", ")", ":", "hit", "=", "_multiply", "(", "target_csr", ",", "assigne...
compare targets and recommendation assignments on user-item matrix
[ "compare", "targets", "and", "recommendation", "assignments", "on", "user", "-", "item", "matrix" ]
[ "\"\"\" compare targets and recommendation assignments on user-item matrix\n \"\"\"", "# 1 by n_items", "# n_users by 1" ]
[ { "param": "target_csr", "type": null }, { "param": "assigned_csr", "type": null }, { "param": "score_mat", "type": null }, { "param": "axis", "type": null }, { "param": "min_total_recs", "type": null }, { "param": "device", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "target_csr", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "assigned_csr", "type": null, "docstring": null, "docstr...
15d4548378162c99a38b5462f5c35c495d7638d9
yifeim/recurrent-intensity-model-experiments
src/rime/util/__init__.py
[ "Apache-2.0" ]
Python
create_matrix
<not_specific>
def create_matrix(event_df, user_index, item_index, return_type='csr'): """ create matrix and prune unknown indices """ user2ind = {k: i for i, k in enumerate(user_index)} item2ind = {k: i for i, k in enumerate(item_index)} event_df = event_df[ event_df['USER_ID'].isin(set(user_index)) & ...
create matrix and prune unknown indices
create matrix and prune unknown indices
[ "create", "matrix", "and", "prune", "unknown", "indices" ]
def create_matrix(event_df, user_index, item_index, return_type='csr'): user2ind = {k: i for i, k in enumerate(user_index)} item2ind = {k: i for i, k in enumerate(item_index)} event_df = event_df[ event_df['USER_ID'].isin(set(user_index)) & event_df['ITEM_ID'].isin(set(item_index)) ] ...
[ "def", "create_matrix", "(", "event_df", ",", "user_index", ",", "item_index", ",", "return_type", "=", "'csr'", ")", ":", "user2ind", "=", "{", "k", ":", "i", "for", "i", ",", "k", "in", "enumerate", "(", "user_index", ")", "}", "item2ind", "=", "{", ...
create matrix and prune unknown indices
[ "create", "matrix", "and", "prune", "unknown", "indices" ]
[ "\"\"\" create matrix and prune unknown indices \"\"\"" ]
[ { "param": "event_df", "type": null }, { "param": "user_index", "type": null }, { "param": "item_index", "type": null }, { "param": "return_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "event_df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "user_index", "type": null, "docstring": null, "docstring_...
15d4548378162c99a38b5462f5c35c495d7638d9
yifeim/recurrent-intensity-model-experiments
src/rime/util/__init__.py
[ "Apache-2.0" ]
Python
filter_min_len
<not_specific>
def filter_min_len(event_df, min_user_len, min_item_len): """ CAVEAT: use in conjunction with dataclass filter to avoid future-leaking bias """ users = event_df.groupby('USER_ID').size() items = event_df.groupby('ITEM_ID').size() return event_df[ event_df['USER_ID'].isin(users[users >= min_user_...
CAVEAT: use in conjunction with dataclass filter to avoid future-leaking bias
use in conjunction with dataclass filter to avoid future-leaking bias
[ "use", "in", "conjunction", "with", "dataclass", "filter", "to", "avoid", "future", "-", "leaking", "bias" ]
def filter_min_len(event_df, min_user_len, min_item_len): users = event_df.groupby('USER_ID').size() items = event_df.groupby('ITEM_ID').size() return event_df[ event_df['USER_ID'].isin(users[users >= min_user_len].index) & event_df['ITEM_ID'].isin(items[items >= min_item_len].index) ]
[ "def", "filter_min_len", "(", "event_df", ",", "min_user_len", ",", "min_item_len", ")", ":", "users", "=", "event_df", ".", "groupby", "(", "'USER_ID'", ")", ".", "size", "(", ")", "items", "=", "event_df", ".", "groupby", "(", "'ITEM_ID'", ")", ".", "s...
CAVEAT: use in conjunction with dataclass filter to avoid future-leaking bias
[ "CAVEAT", ":", "use", "in", "conjunction", "with", "dataclass", "filter", "to", "avoid", "future", "-", "leaking", "bias" ]
[ "\"\"\" CAVEAT: use in conjunction with dataclass filter to avoid future-leaking bias \"\"\"" ]
[ { "param": "event_df", "type": null }, { "param": "min_user_len", "type": null }, { "param": "min_item_len", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "event_df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "min_user_len", "type": null, "docstring": null, "docstrin...
15d4548378162c99a38b5462f5c35c495d7638d9
yifeim/recurrent-intensity-model-experiments
src/rime/util/__init__.py
[ "Apache-2.0" ]
Python
explode_user_titles
<not_specific>
def explode_user_titles(user_hist, item_titles, gamma=0.5, min_gamma=0.1, pad_title='???'): """ explode last few user events and match with item titles; return splits and discount weights; empty user_hist will be turned into a single pad_title. """ keep_last = int(np.log(min_gamma) / np.log(np.clip(gamma, ...
explode last few user events and match with item titles; return splits and discount weights; empty user_hist will be turned into a single pad_title.
explode last few user events and match with item titles; return splits and discount weights; empty user_hist will be turned into a single pad_title.
[ "explode", "last", "few", "user", "events", "and", "match", "with", "item", "titles", ";", "return", "splits", "and", "discount", "weights", ";", "empty", "user_hist", "will", "be", "turned", "into", "a", "single", "pad_title", "." ]
def explode_user_titles(user_hist, item_titles, gamma=0.5, min_gamma=0.1, pad_title='???'): keep_last = int(np.log(min_gamma) / np.log(np.clip(gamma, 1e-10, 1 - 1e-10))) + 1 explode_titles = pd.Series([x[-keep_last:] for x in user_hist.values]).explode() \ .to_frame('ITEM_ID').join(item_titles.to_fram...
[ "def", "explode_user_titles", "(", "user_hist", ",", "item_titles", ",", "gamma", "=", "0.5", ",", "min_gamma", "=", "0.1", ",", "pad_title", "=", "'???'", ")", ":", "keep_last", "=", "int", "(", "np", ".", "log", "(", "min_gamma", ")", "/", "np", ".",...
explode last few user events and match with item titles; return splits and discount weights; empty user_hist will be turned into a single pad_title.
[ "explode", "last", "few", "user", "events", "and", "match", "with", "item", "titles", ";", "return", "splits", "and", "discount", "weights", ";", "empty", "user_hist", "will", "be", "turned", "into", "a", "single", "pad_title", "." ]
[ "\"\"\" explode last few user events and match with item titles;\n return splits and discount weights; empty user_hist will be turned into a single pad_title. \"\"\"", "# default=4", "# -2, -1, 0" ]
[ { "param": "user_hist", "type": null }, { "param": "item_titles", "type": null }, { "param": "gamma", "type": null }, { "param": "min_gamma", "type": null }, { "param": "pad_title", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "user_hist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "item_titles", "type": null, "docstring": null, "docstrin...
b47264792b0f44c362b86101519836b760fe1fc3
yifeim/recurrent-intensity-model-experiments
src/rime/models/graph_conv.py
[ "Apache-2.0" ]
Python
_extract_features
<not_specific>
def _extract_features(self, D): """ create item -> user graph; allow same USER_ID with different TEST_START_TIME """ user_non_empty = D.user_in_test.reset_index()[D.user_in_test['_hist_len'].values > 0] past_event_df = user_non_empty['_hist_items'].explode().to_frame("ITEM_ID") past_eve...
create item -> user graph; allow same USER_ID with different TEST_START_TIME
create item -> user graph; allow same USER_ID with different TEST_START_TIME
[ "create", "item", "-", ">", "user", "graph", ";", "allow", "same", "USER_ID", "with", "different", "TEST_START_TIME" ]
def _extract_features(self, D): user_non_empty = D.user_in_test.reset_index()[D.user_in_test['_hist_len'].values > 0] past_event_df = user_non_empty['_hist_items'].explode().to_frame("ITEM_ID") past_event_df["TIMESTAMP"] = user_non_empty['_hist_ts'].explode().values past_event_df = past_...
[ "def", "_extract_features", "(", "self", ",", "D", ")", ":", "user_non_empty", "=", "D", ".", "user_in_test", ".", "reset_index", "(", ")", "[", "D", ".", "user_in_test", "[", "'_hist_len'", "]", ".", "values", ">", "0", "]", "past_event_df", "=", "user_...
create item -> user graph; allow same USER_ID with different TEST_START_TIME
[ "create", "item", "-", ">", "user", "graph", ";", "allow", "same", "USER_ID", "with", "different", "TEST_START_TIME" ]
[ "\"\"\" create item -> user graph; allow same USER_ID with different TEST_START_TIME \"\"\"", "# item embeddings are shared for different times", "# drop oov items", "# add padding item to guard against users with empty histories" ]
[ { "param": "self", "type": null }, { "param": "D", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "D", "type": null, "docstring": null, "docstring_tokens": [], ...
c3584743e6b2bdb027b5a8ced7640c465393b50a
yifeim/recurrent-intensity-model-experiments
src/rime/models/hawkes.py
[ "Apache-2.0" ]
Python
_input_fn
<not_specific>
def _input_fn(hist_ts, test_start_time, horizon, training, training_eps, hetero): """ format to data and ctrl channels relative to the first observation """ if len(hist_ts): data = (np.array(hist_ts[1:]) - hist_ts[0]) / horizon end_time = (test_start_time - hist_ts[0]) / horizon else: # use...
format to data and ctrl channels relative to the first observation
format to data and ctrl channels relative to the first observation
[ "format", "to", "data", "and", "ctrl", "channels", "relative", "to", "the", "first", "observation" ]
def _input_fn(hist_ts, test_start_time, horizon, training, training_eps, hetero): if len(hist_ts): data = (np.array(hist_ts[1:]) - hist_ts[0]) / horizon end_time = (test_start_time - hist_ts[0]) / horizon else: data = np.array([], dtype=np.asarray(test_start_time).dtype) end_ti...
[ "def", "_input_fn", "(", "hist_ts", ",", "test_start_time", ",", "horizon", ",", "training", ",", "training_eps", ",", "hetero", ")", ":", "if", "len", "(", "hist_ts", ")", ":", "data", "=", "(", "np", ".", "array", "(", "hist_ts", "[", "1", ":", "]"...
format to data and ctrl channels relative to the first observation
[ "format", "to", "data", "and", "ctrl", "channels", "relative", "to", "the", "first", "observation" ]
[ "\"\"\" format to data and ctrl channels relative to the first observation \"\"\"", "# users without histories will receive baseline intensity predictions" ]
[ { "param": "hist_ts", "type": null }, { "param": "test_start_time", "type": null }, { "param": "horizon", "type": null }, { "param": "training", "type": null }, { "param": "training_eps", "type": null }, { "param": "hetero", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "hist_ts", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "test_start_time", "type": null, "docstring": null, "docstr...
fb2661a8acbd8fabf6931e5249331805167c19d7
yifeim/recurrent-intensity-model-experiments
src/rime/__init__.py
[ "Apache-2.0" ]
Python
_mtch_update
<not_specific>
def _mtch_update(self, target_csr, score_mat, valid_mat, name): """ assign user/item matches and return evaluation results. """ confs = [] for m in self.mult: if m < 1: # lower-bound is interpreted as item min-exposure confs.append((self._k1, s...
assign user/item matches and return evaluation results.
assign user/item matches and return evaluation results.
[ "assign", "user", "/", "item", "matches", "and", "return", "evaluation", "results", "." ]
def _mtch_update(self, target_csr, score_mat, valid_mat, name): confs = [] for m in self.mult: if m < 1: confs.append((self._k1, self._c1 * m, 'lb')) else: confs.append((self._k1 * m, self._c1, 'ub')) mtch_kw = self.mtch_kw.copy() i...
[ "def", "_mtch_update", "(", "self", ",", "target_csr", ",", "score_mat", ",", "valid_mat", ",", "name", ")", ":", "confs", "=", "[", "]", "for", "m", "in", "self", ".", "mult", ":", "if", "m", "<", "1", ":", "confs", ".", "append", "(", "(", "sel...
assign user/item matches and return evaluation results.
[ "assign", "user", "/", "item", "matches", "and", "return", "evaluation", "results", "." ]
[ "\"\"\" assign user/item matches and return evaluation results.\n \"\"\"", "# lower-bound is interpreted as item min-exposure", "# upper-bound is interpreted as user max-limit" ]
[ { "param": "self", "type": null }, { "param": "target_csr", "type": null }, { "param": "score_mat", "type": null }, { "param": "valid_mat", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "target_csr", "type": null, "docstring": null, "docstring_toke...
fb2661a8acbd8fabf6931e5249331805167c19d7
yifeim/recurrent-intensity-model-experiments
src/rime/__init__.py
[ "Apache-2.0" ]
Python
run
null
def run(self, models_to_run=None, models_to_exclude=["ItemKNN-0", "ItemKNN-1", "BayesLM-0", "BayesLM-1"]): """ models_to_exclude is ignored if models_to_run is explicitly provided """ if models_to_run is None: models_to_run = [m for m in self.models_to_run if m not in models_to_...
models_to_exclude is ignored if models_to_run is explicitly provided
models_to_exclude is ignored if models_to_run is explicitly provided
[ "models_to_exclude", "is", "ignored", "if", "models_to_run", "is", "explicitly", "provided" ]
def run(self, models_to_run=None, models_to_exclude=["ItemKNN-0", "ItemKNN-1", "BayesLM-0", "BayesLM-1"]): if models_to_run is None: models_to_run = [m for m in self.models_to_run if m not in models_to_exclude] elif isinstance(models_to_run, str): models_to_run = [mod...
[ "def", "run", "(", "self", ",", "models_to_run", "=", "None", ",", "models_to_exclude", "=", "[", "\"ItemKNN-0\"", ",", "\"ItemKNN-1\"", ",", "\"BayesLM-0\"", ",", "\"BayesLM-1\"", "]", ")", ":", "if", "models_to_run", "is", "None", ":", "models_to_run", "=", ...
models_to_exclude is ignored if models_to_run is explicitly provided
[ "models_to_exclude", "is", "ignored", "if", "models_to_run", "is", "explicitly", "provided" ]
[ "\"\"\" models_to_exclude is ignored if models_to_run is explicitly provided \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "models_to_run", "type": null }, { "param": "models_to_exclude", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "models_to_run", "type": null, "docstring": null, "docstring_t...
5af607b92805ce4485db07f0c85ab0b99fda41c6
yifeim/recurrent-intensity-model-experiments
src/rime/models/zero_shot/item_knn.py
[ "Apache-2.0" ]
Python
_compute_embeddings
<not_specific>
def _compute_embeddings(self, titles): """ find embedding of a batch of sequences """ with _to_cuda(self.model) as model: embeddings = [] for batch in tqdm(np.split(titles, range(0, len(titles), self.batch_size)[1:])): inputs = self.tokenizer(batch.tolist(), padd...
find embedding of a batch of sequences
find embedding of a batch of sequences
[ "find", "embedding", "of", "a", "batch", "of", "sequences" ]
def _compute_embeddings(self, titles): with _to_cuda(self.model) as model: embeddings = [] for batch in tqdm(np.split(titles, range(0, len(titles), self.batch_size)[1:])): inputs = self.tokenizer(batch.tolist(), padding=True, return_tensors='pt') if hasatt...
[ "def", "_compute_embeddings", "(", "self", ",", "titles", ")", ":", "with", "_to_cuda", "(", "self", ".", "model", ")", "as", "model", ":", "embeddings", "=", "[", "]", "for", "batch", "in", "tqdm", "(", "np", ".", "split", "(", "titles", ",", "range...
find embedding of a batch of sequences
[ "find", "embedding", "of", "a", "batch", "of", "sequences" ]
[ "\"\"\" find embedding of a batch of sequences \"\"\"", "# 'input_ids', 'attention_mask', 'token_type_ids'", "# [cls] seq [sep]", "# mean-pooling on causal lm states" ]
[ { "param": "self", "type": null }, { "param": "titles", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "titles", "type": null, "docstring": null, "docstring_tokens":...
42ce983f7bfa4ffd8b8b965ce05e147047697b8a
yifeim/recurrent-intensity-model-experiments
src/rime/models/lda.py
[ "Apache-2.0" ]
Python
fit
<not_specific>
def fit(self, D): """ learn from training_data on gpu w/ mini-batches; clear gpu in the end """ user_index = D.user_df[D.user_df['_hist_len'] > 0].index # prune empty users i, j = create_matrix(D.event_df, user_index, self._item_list, 'ij') G = dgl.heterograph( {('doc', '',...
learn from training_data on gpu w/ mini-batches; clear gpu in the end
learn from training_data on gpu w/ mini-batches; clear gpu in the end
[ "learn", "from", "training_data", "on", "gpu", "w", "/", "mini", "-", "batches", ";", "clear", "gpu", "in", "the", "end" ]
def fit(self, D): user_index = D.user_df[D.user_df['_hist_len'] > 0].index i, j = create_matrix(D.event_df, user_index, self._item_list, 'ij') G = dgl.heterograph( {('doc', '', 'word'): (i, j)}, {'doc': len(user_index), 'word': len(self._item_list)}, ) l...
[ "def", "fit", "(", "self", ",", "D", ")", ":", "user_index", "=", "D", ".", "user_df", "[", "D", ".", "user_df", "[", "'_hist_len'", "]", ">", "0", "]", ".", "index", "i", ",", "j", "=", "create_matrix", "(", "D", ".", "event_df", ",", "user_inde...
learn from training_data on gpu w/ mini-batches; clear gpu in the end
[ "learn", "from", "training_data", "on", "gpu", "w", "/", "mini", "-", "batches", ";", "clear", "gpu", "in", "the", "end" ]
[ "\"\"\" learn from training_data on gpu w/ mini-batches; clear gpu in the end \"\"\"", "# prune empty users" ]
[ { "param": "self", "type": null }, { "param": "D", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "D", "type": null, "docstring": null, "docstring_tokens": [], ...
42ce983f7bfa4ffd8b8b965ce05e147047697b8a
yifeim/recurrent-intensity-model-experiments
src/rime/models/lda.py
[ "Apache-2.0" ]
Python
transform
<not_specific>
def transform(self, D, return_doc_data=False): """ run e-step to get doc data; output as low-rank nonnegative matrix """ user_non_empty = D.user_in_test.reset_index()[D.user_in_test['_hist_len'].values > 0] past_event_df = user_non_empty['_hist_items'].explode().to_frame("ITEM_ID").join( ...
run e-step to get doc data; output as low-rank nonnegative matrix
run e-step to get doc data; output as low-rank nonnegative matrix
[ "run", "e", "-", "step", "to", "get", "doc", "data", ";", "output", "as", "low", "-", "rank", "nonnegative", "matrix" ]
def transform(self, D, return_doc_data=False): user_non_empty = D.user_in_test.reset_index()[D.user_in_test['_hist_len'].values > 0] past_event_df = user_non_empty['_hist_items'].explode().to_frame("ITEM_ID").join( pd.Series({k: j for j, k in enumerate(self._item_list)}).to_frame("j"), ...
[ "def", "transform", "(", "self", ",", "D", ",", "return_doc_data", "=", "False", ")", ":", "user_non_empty", "=", "D", ".", "user_in_test", ".", "reset_index", "(", ")", "[", "D", ".", "user_in_test", "[", "'_hist_len'", "]", ".", "values", ">", "0", "...
run e-step to get doc data; output as low-rank nonnegative matrix
[ "run", "e", "-", "step", "to", "get", "doc", "data", ";", "output", "as", "low", "-", "rank", "nonnegative", "matrix" ]
[ "\"\"\" run e-step to get doc data; output as low-rank nonnegative matrix \"\"\"", "# drop oov items" ]
[ { "param": "self", "type": null }, { "param": "D", "type": null }, { "param": "return_doc_data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "D", "type": null, "docstring": null, "docstring_tokens": [], ...
53d09b9a1a4b58b11313dab158d1ef6150435bbd
yifeim/recurrent-intensity-model-experiments
src/rime/dataset/base.py
[ "Apache-2.0" ]
Python
_augment_item_hist
<not_specific>
def _augment_item_hist(item_df, event_df): """ augment history inferred from training set """ return item_df.join( event_df[event_df['_holdout'] == 0] .groupby('ITEM_ID').size().to_frame('_hist_len') ).fillna({'_hist_len': 0})
augment history inferred from training set
augment history inferred from training set
[ "augment", "history", "inferred", "from", "training", "set" ]
def _augment_item_hist(item_df, event_df): return item_df.join( event_df[event_df['_holdout'] == 0] .groupby('ITEM_ID').size().to_frame('_hist_len') ).fillna({'_hist_len': 0})
[ "def", "_augment_item_hist", "(", "item_df", ",", "event_df", ")", ":", "return", "item_df", ".", "join", "(", "event_df", "[", "event_df", "[", "'_holdout'", "]", "==", "0", "]", ".", "groupby", "(", "'ITEM_ID'", ")", ".", "size", "(", ")", ".", "to_f...
augment history inferred from training set
[ "augment", "history", "inferred", "from", "training", "set" ]
[ "\"\"\" augment history inferred from training set \"\"\"" ]
[ { "param": "item_df", "type": null }, { "param": "event_df", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "item_df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "event_df", "type": null, "docstring": null, "docstring_tok...
53d09b9a1a4b58b11313dab158d1ef6150435bbd
yifeim/recurrent-intensity-model-experiments
src/rime/dataset/base.py
[ "Apache-2.0" ]
Python
create_dataset
<not_specific>
def create_dataset(event_df, user_df, item_df, horizon=float("inf"), min_user_len=1, min_item_len=1, prior_score=None, exclude_train=False, test_incl_users_with_posinf_test_time=False, test_incl_users_with_neginf_test_time=True, ): """ Crea...
Create a labeled dataset from 3 related tables and additional configurations. :parameter event_df: [USER_ID, ITEM_ID, TIMESTAMP] :parameter user_df: [USER_ID (index), TEST_START_TIME] :parameter item_df: [ITEM_ID (index)] :parameter horizon: extract test window from TIMESTAMP, TEST_START_TIME, and hor...
Create a labeled dataset from 3 related tables and additional configurations.
[ "Create", "a", "labeled", "dataset", "from", "3", "related", "tables", "and", "additional", "configurations", "." ]
def create_dataset(event_df, user_df, item_df, horizon=float("inf"), min_user_len=1, min_item_len=1, prior_score=None, exclude_train=False, test_incl_users_with_posinf_test_time=False, test_incl_users_with_neginf_test_time=True, ): _check_i...
[ "def", "create_dataset", "(", "event_df", ",", "user_df", ",", "item_df", ",", "horizon", "=", "float", "(", "\"inf\"", ")", ",", "min_user_len", "=", "1", ",", "min_item_len", "=", "1", ",", "prior_score", "=", "None", ",", "exclude_train", "=", "False", ...
Create a labeled dataset from 3 related tables and additional configurations.
[ "Create", "a", "labeled", "dataset", "from", "3", "related", "tables", "and", "additional", "configurations", "." ]
[ "\"\"\" Create a labeled dataset from 3 related tables and additional configurations.\n\n :parameter event_df: [USER_ID, ITEM_ID, TIMESTAMP]\n :parameter user_df: [USER_ID (index), TEST_START_TIME]\n :parameter item_df: [ITEM_ID (index)]\n :parameter horizon: extract test window from TIMESTAMP, TEST_STA...
[ { "param": "event_df", "type": null }, { "param": "user_df", "type": null }, { "param": "item_df", "type": null }, { "param": "horizon", "type": null }, { "param": "min_user_len", "type": null }, { "param": "min_item_len", "type": null }, { ...
{ "returns": [], "raises": [], "params": [ { "identifier": "event_df", "type": null, "docstring": "[USER_ID, ITEM_ID, TIMESTAMP]", "docstring_tokens": [ "[", "USER_ID", "ITEM_ID", "TIMESTAMP", "]" ], "default": null, "is_optiona...
6d3c4f7075bd2652d704f6cdbcdfd83999d8fd77
yifeim/recurrent-intensity-model-experiments
src/rime/util/score_array.py
[ "Apache-2.0" ]
Python
matrix_reindex
<not_specific>
def matrix_reindex(csr, old_index, new_index, axis, fill_value=0): """ pandas.reindex functionality on sparse or dense matrices as well as 1d arrays """ if axis == 1: return matrix_reindex(csr.T, old_index, new_index, 0, fill_value).T.copy() assert axis == 0, "axis must be 0 or 1" assert csr.sha...
pandas.reindex functionality on sparse or dense matrices as well as 1d arrays
pandas.reindex functionality on sparse or dense matrices as well as 1d arrays
[ "pandas", ".", "reindex", "functionality", "on", "sparse", "or", "dense", "matrices", "as", "well", "as", "1d", "arrays" ]
def matrix_reindex(csr, old_index, new_index, axis, fill_value=0): if axis == 1: return matrix_reindex(csr.T, old_index, new_index, 0, fill_value).T.copy() assert axis == 0, "axis must be 0 or 1" assert csr.shape[0] == len(old_index), "shape must match between csr and old_index" if sps.issparse(...
[ "def", "matrix_reindex", "(", "csr", ",", "old_index", ",", "new_index", ",", "axis", ",", "fill_value", "=", "0", ")", ":", "if", "axis", "==", "1", ":", "return", "matrix_reindex", "(", "csr", ".", "T", ",", "old_index", ",", "new_index", ",", "0", ...
pandas.reindex functionality on sparse or dense matrices as well as 1d arrays
[ "pandas", ".", "reindex", "functionality", "on", "sparse", "or", "dense", "matrices", "as", "well", "as", "1d", "arrays" ]
[ "\"\"\" pandas.reindex functionality on sparse or dense matrices as well as 1d arrays \"\"\"" ]
[ { "param": "csr", "type": null }, { "param": "old_index", "type": null }, { "param": "new_index", "type": null }, { "param": "axis", "type": null }, { "param": "fill_value", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "csr", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "old_index", "type": null, "docstring": null, "docstring_tokens...
33233258215b7d1a6092c1fecfbda1a3e065af4a
yifeim/recurrent-intensity-model-experiments
src/rime/util/plotting.py
[ "Apache-2.0" ]
Python
plot_rec_results
<not_specific>
def plot_rec_results(self, metric_name='recall'): """ self is an instance of Experiment or ExperimentResult """ ir = pd.DataFrame(self.item_rec).T ur = pd.DataFrame(self.user_rec).T df = ir[[metric_name]] * 100 axname_itemrec = f"ItemRec {metric_name}@{self._k1} (x100)" axname_userrec = f'UserRe...
self is an instance of Experiment or ExperimentResult
self is an instance of Experiment or ExperimentResult
[ "self", "is", "an", "instance", "of", "Experiment", "or", "ExperimentResult" ]
def plot_rec_results(self, metric_name='recall'): ir = pd.DataFrame(self.item_rec).T ur = pd.DataFrame(self.user_rec).T df = ir[[metric_name]] * 100 axname_itemrec = f"ItemRec {metric_name}@{self._k1} (x100)" axname_userrec = f'UserRec {metric_name}@{self._c1} (x100)' df = df.rename(columns={met...
[ "def", "plot_rec_results", "(", "self", ",", "metric_name", "=", "'recall'", ")", ":", "ir", "=", "pd", ".", "DataFrame", "(", "self", ".", "item_rec", ")", ".", "T", "ur", "=", "pd", ".", "DataFrame", "(", "self", ".", "user_rec", ")", ".", "T", "...
self is an instance of Experiment or ExperimentResult
[ "self", "is", "an", "instance", "of", "Experiment", "or", "ExperimentResult" ]
[ "\"\"\" self is an instance of Experiment or ExperimentResult \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "metric_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "metric_name", "type": null, "docstring": null, "docstring_tok...
33233258215b7d1a6092c1fecfbda1a3e065af4a
yifeim/recurrent-intensity-model-experiments
src/rime/util/plotting.py
[ "Apache-2.0" ]
Python
plot_mtch_results
<not_specific>
def plot_mtch_results(self, logy=True): """ self is an instance of Experiment or ExperimentResult """ fig, ax = plt.subplots(1, 2, figsize=(7, 2.5)) df = [self.get_mtch_(k=self._k1), self.get_mtch_(c=self._c1)] xname = [f'ItemRec Prec@{self._k1}', f'UserRec Prec@{self._c1}'] yname = ['item_ppl', 'u...
self is an instance of Experiment or ExperimentResult
self is an instance of Experiment or ExperimentResult
[ "self", "is", "an", "instance", "of", "Experiment", "or", "ExperimentResult" ]
def plot_mtch_results(self, logy=True): fig, ax = plt.subplots(1, 2, figsize=(7, 2.5)) df = [self.get_mtch_(k=self._k1), self.get_mtch_(c=self._c1)] xname = [f'ItemRec Prec@{self._k1}', f'UserRec Prec@{self._c1}'] yname = ['item_ppl', 'user_ppl'] for ax, df, xname, yname in zip(ax, df, xname, yname)...
[ "def", "plot_mtch_results", "(", "self", ",", "logy", "=", "True", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "1", ",", "2", ",", "figsize", "=", "(", "7", ",", "2.5", ")", ")", "df", "=", "[", "self", ".", "get_mtch_", "(", ...
self is an instance of Experiment or ExperimentResult
[ "self", "is", "an", "instance", "of", "Experiment", "or", "ExperimentResult" ]
[ "\"\"\" self is an instance of Experiment or ExperimentResult \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "logy", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "logy", "type": null, "docstring": null, "docstring_tokens": [...
41af20611730bb2934ec0ead2099e9063a73ed5d
infosecjosh/plaso
plaso/engine/path_helper.py
[ "Apache-2.0" ]
Python
_ExpandUsersHomeDirectoryPathSegments
<not_specific>
def _ExpandUsersHomeDirectoryPathSegments( cls, path_segments, path_separator, user_accounts): """Expands a path to contain all users home or profile directories. Expands the artifacts path variable "%%users.homedir%%" or "%%users.userprofile%%". Args: path_segments (list[str]): path segme...
Expands a path to contain all users home or profile directories. Expands the artifacts path variable "%%users.homedir%%" or "%%users.userprofile%%". Args: path_segments (list[str]): path segments. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): us...
Expands a path to contain all users home or profile directories.
[ "Expands", "a", "path", "to", "contain", "all", "users", "home", "or", "profile", "directories", "." ]
def _ExpandUsersHomeDirectoryPathSegments( cls, path_segments, path_separator, user_accounts): if not path_segments: return [] user_paths = [] first_path_segment = path_segments[0].upper() if first_path_segment not in ('%%USERS.HOMEDIR%%', '%%USERS.USERPROFILE%%'): user_path = path_sep...
[ "def", "_ExpandUsersHomeDirectoryPathSegments", "(", "cls", ",", "path_segments", ",", "path_separator", ",", "user_accounts", ")", ":", "if", "not", "path_segments", ":", "return", "[", "]", "user_paths", "=", "[", "]", "first_path_segment", "=", "path_segments", ...
Expands a path to contain all users home or profile directories.
[ "Expands", "a", "path", "to", "contain", "all", "users", "home", "or", "profile", "directories", "." ]
[ "\"\"\"Expands a path to contain all users home or profile directories.\n\n Expands the artifacts path variable \"%%users.homedir%%\" or\n \"%%users.userprofile%%\".\n\n Args:\n path_segments (list[str]): path segments.\n path_separator (str): path segment separator.\n user_accounts (list[Us...
[ { "param": "cls", "type": null }, { "param": "path_segments", "type": null }, { "param": "path_separator", "type": null }, { "param": "user_accounts", "type": null } ]
{ "returns": [ { "docstring": "paths returned for user accounts without a drive letter.", "docstring_tokens": [ "paths", "returned", "for", "user", "accounts", "without", "a", "drive", "letter", "." ], "type": ...
41af20611730bb2934ec0ead2099e9063a73ed5d
infosecjosh/plaso
plaso/engine/path_helper.py
[ "Apache-2.0" ]
Python
_ExpandUsersVariablePathSegments
<not_specific>
def _ExpandUsersVariablePathSegments( cls, path_segments, path_separator, user_accounts): """Expands path segments with a users variable, e.g. %%users.homedir%%. Args: path_segments (list[str]): path segments. path_separator (str): path segment separator. user_accounts (list[UserAccount...
Expands path segments with a users variable, e.g. %%users.homedir%%. Args: path_segments (list[str]): path segments. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): user accounts. Returns: list[str]: paths for which the users variables have been...
Expands path segments with a users variable, e.g.
[ "Expands", "path", "segments", "with", "a", "users", "variable", "e", ".", "g", "." ]
def _ExpandUsersVariablePathSegments( cls, path_segments, path_separator, user_accounts): if not path_segments: return [] if path_segments[0] in ('%%users.homedir%%', '%%users.userprofile%%'): return cls._ExpandUsersHomeDirectoryPathSegments( path_segments, path_separator, user_accou...
[ "def", "_ExpandUsersVariablePathSegments", "(", "cls", ",", "path_segments", ",", "path_separator", ",", "user_accounts", ")", ":", "if", "not", "path_segments", ":", "return", "[", "]", "if", "path_segments", "[", "0", "]", "in", "(", "'%%users.homedir%%'", ","...
Expands path segments with a users variable, e.g.
[ "Expands", "path", "segments", "with", "a", "users", "variable", "e", ".", "g", "." ]
[ "\"\"\"Expands path segments with a users variable, e.g. %%users.homedir%%.\n\n Args:\n path_segments (list[str]): path segments.\n path_separator (str): path segment separator.\n user_accounts (list[UserAccountArtifact]): user accounts.\n\n Returns:\n list[str]: paths for which the users ...
[ { "param": "cls", "type": null }, { "param": "path_segments", "type": null }, { "param": "path_separator", "type": null }, { "param": "user_accounts", "type": null } ]
{ "returns": [ { "docstring": "paths for which the users variables have been expanded.", "docstring_tokens": [ "paths", "for", "which", "the", "users", "variables", "have", "been", "expanded", "." ], "type": "l...
41af20611730bb2934ec0ead2099e9063a73ed5d
infosecjosh/plaso
plaso/engine/path_helper.py
[ "Apache-2.0" ]
Python
_StripDriveFromPath
<not_specific>
def _StripDriveFromPath(cls, path): """Removes a leading drive letter or %SystemDrive% from the path. Args: path (str): path. Returns: str: path without leading drive letter or %SystemDrive%. """ if len(path) >= 2 and path[1] == ':': return path[2:] path_upper_case = path.up...
Removes a leading drive letter or %SystemDrive% from the path. Args: path (str): path. Returns: str: path without leading drive letter or %SystemDrive%.
Removes a leading drive letter or %SystemDrive% from the path.
[ "Removes", "a", "leading", "drive", "letter", "or", "%SystemDrive%", "from", "the", "path", "." ]
def _StripDriveFromPath(cls, path): if len(path) >= 2 and path[1] == ':': return path[2:] path_upper_case = path.upper() if path_upper_case.startswith('%%ENVIRON_SYSTEMDRIVE%%\\'): return path[23:] if path_upper_case.startswith('%SYSTEMDRIVE%\\'): return path[13:] return path
[ "def", "_StripDriveFromPath", "(", "cls", ",", "path", ")", ":", "if", "len", "(", "path", ")", ">=", "2", "and", "path", "[", "1", "]", "==", "':'", ":", "return", "path", "[", "2", ":", "]", "path_upper_case", "=", "path", ".", "upper", "(", ")...
Removes a leading drive letter or %SystemDrive% from the path.
[ "Removes", "a", "leading", "drive", "letter", "or", "%SystemDrive%", "from", "the", "path", "." ]
[ "\"\"\"Removes a leading drive letter or %SystemDrive% from the path.\n\n Args:\n path (str): path.\n\n Returns:\n str: path without leading drive letter or %SystemDrive%.\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "path", "type": null } ]
{ "returns": [ { "docstring": "path without leading drive letter or %SystemDrive%.", "docstring_tokens": [ "path", "without", "leading", "drive", "letter", "or", "%SystemDrive%", "." ], "type": "str" } ], "raises": [],...
41af20611730bb2934ec0ead2099e9063a73ed5d
infosecjosh/plaso
plaso/engine/path_helper.py
[ "Apache-2.0" ]
Python
ExpandUsersVariablePath
<not_specific>
def ExpandUsersVariablePath(cls, path, path_separator, user_accounts): """Expands a path with a users variable, e.g. %%users.homedir%%. Args: path (str): path with users variable. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): user accounts. Retu...
Expands a path with a users variable, e.g. %%users.homedir%%. Args: path (str): path with users variable. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): user accounts. Returns: list[str]: paths for which the users variables have been expanded. ...
Expands a path with a users variable, e.g.
[ "Expands", "a", "path", "with", "a", "users", "variable", "e", ".", "g", "." ]
def ExpandUsersVariablePath(cls, path, path_separator, user_accounts): path_segments = path.split(path_separator) return cls._ExpandUsersVariablePathSegments( path_segments, path_separator, user_accounts)
[ "def", "ExpandUsersVariablePath", "(", "cls", ",", "path", ",", "path_separator", ",", "user_accounts", ")", ":", "path_segments", "=", "path", ".", "split", "(", "path_separator", ")", "return", "cls", ".", "_ExpandUsersVariablePathSegments", "(", "path_segments", ...
Expands a path with a users variable, e.g.
[ "Expands", "a", "path", "with", "a", "users", "variable", "e", ".", "g", "." ]
[ "\"\"\"Expands a path with a users variable, e.g. %%users.homedir%%.\n\n Args:\n path (str): path with users variable.\n path_separator (str): path segment separator.\n user_accounts (list[UserAccountArtifact]): user accounts.\n\n Returns:\n list[str]: paths for which the users variables h...
[ { "param": "cls", "type": null }, { "param": "path", "type": null }, { "param": "path_separator", "type": null }, { "param": "user_accounts", "type": null } ]
{ "returns": [ { "docstring": "paths for which the users variables have been expanded.", "docstring_tokens": [ "paths", "for", "which", "the", "users", "variables", "have", "been", "expanded", "." ], "type": "l...
1fdab186fba10825bb835fc8f261be40bac2bb44
zhen-xie/DeepSpeed
deepspeed/runtime/engine.py
[ "MIT" ]
Python
was_step_applied
bool
def was_step_applied(self) -> bool: """Returns True if the latest ``step()`` produced in parameter updates. Note that a ``False`` return is not an error condition. Steps are frequently no-ops, such as between gradient accumulation boundaries or when overflows occur. Returns: ...
Returns True if the latest ``step()`` produced in parameter updates. Note that a ``False`` return is not an error condition. Steps are frequently no-ops, such as between gradient accumulation boundaries or when overflows occur. Returns: bool: Whether the latest ``step()`` m...
Returns True if the latest ``step()`` produced in parameter updates. Note that a ``False`` return is not an error condition. Steps are frequently no-ops, such as between gradient accumulation boundaries or when overflows occur.
[ "Returns", "True", "if", "the", "latest", "`", "`", "step", "()", "`", "`", "produced", "in", "parameter", "updates", ".", "Note", "that", "a", "`", "`", "False", "`", "`", "return", "is", "not", "an", "error", "condition", ".", "Steps", "are", "freq...
def was_step_applied(self) -> bool: return self._step_applied
[ "def", "was_step_applied", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_step_applied" ]
Returns True if the latest ``step()`` produced in parameter updates.
[ "Returns", "True", "if", "the", "latest", "`", "`", "step", "()", "`", "`", "produced", "in", "parameter", "updates", "." ]
[ "\"\"\"Returns True if the latest ``step()`` produced in parameter updates.\n\n Note that a ``False`` return is not an error condition. Steps are frequently\n no-ops, such as between gradient accumulation boundaries or when overflows\n occur.\n\n Returns:\n bool: Whether the l...
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "Whether the latest ``step()`` modified model parameters.", "docstring_tokens": [ "Whether", "the", "latest", "`", "`", "step", "()", "`", "`", "modified", "model", "parameters...
1fdab186fba10825bb835fc8f261be40bac2bb44
zhen-xie/DeepSpeed
deepspeed/runtime/engine.py
[ "MIT" ]
Python
step
null
def step(self, lr_kwargs=None): r"""Execute the weight update step after forward and backward propagation on effective_train_batch. """ if self.wall_clock_breakdown(): self.timers('step_microstep').start() self.timers('step').start() assert self.optimizer...
r"""Execute the weight update step after forward and backward propagation on effective_train_batch.
r"""Execute the weight update step after forward and backward propagation on effective_train_batch.
[ "r", "\"", "\"", "\"", "Execute", "the", "weight", "update", "step", "after", "forward", "and", "backward", "propagation", "on", "effective_train_batch", "." ]
def step(self, lr_kwargs=None): if self.wall_clock_breakdown(): self.timers('step_microstep').start() self.timers('step').start() assert self.optimizer is not None, "must provide optimizer during " \ "init in order to use step" r...
[ "def", "step", "(", "self", ",", "lr_kwargs", "=", "None", ")", ":", "if", "self", ".", "wall_clock_breakdown", "(", ")", ":", "self", ".", "timers", "(", "'step_microstep'", ")", ".", "start", "(", ")", "self", ".", "timers", "(", "'step'", ")", "."...
r"""Execute the weight update step after forward and backward propagation on effective_train_batch.
[ "r", "\"", "\"", "\"", "Execute", "the", "weight", "update", "step", "after", "forward", "and", "backward", "propagation", "on", "effective_train_batch", "." ]
[ "r\"\"\"Execute the weight update step after forward and backward propagation\n on effective_train_batch.\n \"\"\"", "# assume False, will flip to True", "# Update the model when we reach gradient accumulation boundaries", "# Log learning rate", "# write_summary_events", "# write_summary_eve...
[ { "param": "self", "type": null }, { "param": "lr_kwargs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "lr_kwargs", "type": null, "docstring": null, "docstring_token...
1fdab186fba10825bb835fc8f261be40bac2bb44
zhen-xie/DeepSpeed
deepspeed/runtime/engine.py
[ "MIT" ]
Python
_get_zero_param_shapes
<not_specific>
def _get_zero_param_shapes(self): """Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the optimizer. the names are exactly as in state_dict. The order is absolutely important, since the saved data is just flattened data with no identifiers and requires recons...
Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the optimizer. the names are exactly as in state_dict. The order is absolutely important, since the saved data is just flattened data with no identifiers and requires reconstruction in the same order it was sav...
Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the optimizer. the names are exactly as in state_dict. The order is absolutely important, since the saved data is just flattened data with no identifiers and requires reconstruction in the same order it was saved. We can't rely on se...
[ "Returns", "a", "dict", "of", "name", "to", "shape", "mapping", "only", "for", "the", "flattened", "fp32", "weights", "saved", "by", "the", "optimizer", ".", "the", "names", "are", "exactly", "as", "in", "state_dict", ".", "The", "order", "is", "absolutely...
def _get_zero_param_shapes(self): param_group_shapes = [] cnt = 0 numel = 0 if hasattr(self.optimizer, "round_robin_fp16_groups"): fp16_groups = self.optimizer.round_robin_fp16_groups else: fp16_groups = self.optimizer.fp16_groups for fp16_group in...
[ "def", "_get_zero_param_shapes", "(", "self", ")", ":", "param_group_shapes", "=", "[", "]", "cnt", "=", "0", "numel", "=", "0", "if", "hasattr", "(", "self", ".", "optimizer", ",", "\"round_robin_fp16_groups\"", ")", ":", "fp16_groups", "=", "self", ".", ...
Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the optimizer.
[ "Returns", "a", "dict", "of", "name", "to", "shape", "mapping", "only", "for", "the", "flattened", "fp32", "weights", "saved", "by", "the", "optimizer", "." ]
[ "\"\"\"Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the\n optimizer. the names are exactly as in state_dict. The order is absolutely important, since\n the saved data is just flattened data with no identifiers and requires reconstruction in the\n same or...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
readYAML
null
def readYAML(self): """Read data from job config YAML and make certain calculations for later use. Stores peg frames in dictionary tool_data """ #job parameters moved in from the peg_in_hole_params.yaml file #'peg_4mm' 'peg_8mm' 'peg_10mm' 'peg_16mm' #'hole_4mm' 'hole_8m...
Read data from job config YAML and make certain calculations for later use. Stores peg frames in dictionary tool_data
Read data from job config YAML and make certain calculations for later use. Stores peg frames in dictionary tool_data
[ "Read", "data", "from", "job", "config", "YAML", "and", "make", "certain", "calculations", "for", "later", "use", ".", "Stores", "peg", "frames", "in", "dictionary", "tool_data" ]
def readYAML(self): self.target_peg = rospy.get_param('/task/target_peg') self.target_hole = rospy.get_param('/task/target_hole') self.activeTCP = rospy.get_param('/task/starting_tcp') self.read_board_positions() self.read_peg_hole_...
[ "def", "readYAML", "(", "self", ")", ":", "self", ".", "target_peg", "=", "rospy", ".", "get_param", "(", "'/task/target_peg'", ")", "self", ".", "target_hole", "=", "rospy", ".", "get_param", "(", "'/task/target_hole'", ")", "self", ".", "activeTCP", "=", ...
Read data from job config YAML and make certain calculations for later use.
[ "Read", "data", "from", "job", "config", "YAML", "and", "make", "certain", "calculations", "for", "later", "use", "." ]
[ "\"\"\"Read data from job config YAML and make certain calculations for later use. Stores peg frames in dictionary tool_data\n \"\"\"", "#job parameters moved in from the peg_in_hole_params.yaml file", "#'peg_4mm' 'peg_8mm' 'peg_10mm' 'peg_16mm'", "#'hole_4mm' 'hole_8mm' 'hole_10mm' 'hole_16mm'", "#S...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
read_board_positions
null
def read_board_positions(self): """ Calculates pose of target hole relative to robot base frame. """ temp_z_position_offset = 207 #Our robot is reading Z positions wrong on the pendant for some reason. taskPos = list(np.array(rospy.get_param('/environment_state/task_frame/position'))) ...
Calculates pose of target hole relative to robot base frame.
Calculates pose of target hole relative to robot base frame.
[ "Calculates", "pose", "of", "target", "hole", "relative", "to", "robot", "base", "frame", "." ]
def read_board_positions(self): temp_z_position_offset = 207 taskPos = list(np.array(rospy.get_param('/environment_state/task_frame/position'))) taskPos[2] = taskPos[2] + temp_z_position_offset taskOri = rospy.get_param('/environment_state/task_frame/orientation') holePos = list...
[ "def", "read_board_positions", "(", "self", ")", ":", "temp_z_position_offset", "=", "207", "taskPos", "=", "list", "(", "np", ".", "array", "(", "rospy", ".", "get_param", "(", "'/environment_state/task_frame/position'", ")", ")", ")", "taskPos", "[", "2", "]...
Calculates pose of target hole relative to robot base frame.
[ "Calculates", "pose", "of", "target", "hole", "relative", "to", "robot", "base", "frame", "." ]
[ "\"\"\" Calculates pose of target hole relative to robot base frame.\n \"\"\"", "#Our robot is reading Z positions wrong on the pendant for some reason.", "#Set up target hole pose", "# self.target_broadcaster = tf2_geometry_msgs.do_transform_pose(self.pose_task_board_to_hole, self.tf_robot_to_task_boa...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
read_peg_hole_dimensions
null
def read_peg_hole_dimensions(self): """Read peg and hole data from YAML configuration file. """ peg_diameter = rospy.get_param('/objects/'+self.target_peg+'/dimensions/diameter')/1000 #mm peg_tol_plus = rospy.get_param('/objects/'+self.target_peg+'/tolerance/upper_toleran...
Read peg and hole data from YAML configuration file.
Read peg and hole data from YAML configuration file.
[ "Read", "peg", "and", "hole", "data", "from", "YAML", "configuration", "file", "." ]
def read_peg_hole_dimensions(self): peg_diameter = rospy.get_param('/objects/'+self.target_peg+'/dimensions/diameter')/1000 peg_tol_plus = rospy.get_param('/objects/'+self.target_peg+'/tolerance/upper_tolerance')/1000 peg_tol_minus = rospy.get_param('/objects/'+self.targe...
[ "def", "read_peg_hole_dimensions", "(", "self", ")", ":", "peg_diameter", "=", "rospy", ".", "get_param", "(", "'/objects/'", "+", "self", ".", "target_peg", "+", "'/dimensions/diameter'", ")", "/", "1000", "peg_tol_plus", "=", "rospy", ".", "get_param", "(", ...
Read peg and hole data from YAML configuration file.
[ "Read", "peg", "and", "hole", "data", "from", "YAML", "configuration", "file", "." ]
[ "\"\"\"Read peg and hole data from YAML configuration file.\n \"\"\"", "#mm", "#mm", "#setup, run to calculate useful values based on params:", "#calculate the total error zone;", "#calculate minimum clearance; =0", "#provisional calculation of \"wiggle room\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
select_tool
null
def select_tool(self, tool_name): """Sets activeTCP frame according to title of desired peg frame (tip, middle, etc.). This frame must be included in the YAML. :param tool_name: (string) Key in tool_data dictionary for desired frame. """ # TODO: Make this a loop-run state to slowly slerp...
Sets activeTCP frame according to title of desired peg frame (tip, middle, etc.). This frame must be included in the YAML. :param tool_name: (string) Key in tool_data dictionary for desired frame.
Sets activeTCP frame according to title of desired peg frame (tip, middle, etc.). This frame must be included in the YAML.
[ "Sets", "activeTCP", "frame", "according", "to", "title", "of", "desired", "peg", "frame", "(", "tip", "middle", "etc", ".", ")", ".", "This", "frame", "must", "be", "included", "in", "the", "YAML", "." ]
def select_tool(self, tool_name): if(tool_name in list(self.tool_data)): self.activeTCP = tool_name self.reference_frames['tcp'] = self.tool_data[self.activeTCP]['transform'] self.send_reference_TFs() else: rospy.logerr_throttle(2, "Tool selection key erro...
[ "def", "select_tool", "(", "self", ",", "tool_name", ")", ":", "if", "(", "tool_name", "in", "list", "(", "self", ".", "tool_data", ")", ")", ":", "self", ".", "activeTCP", "=", "tool_name", "self", ".", "reference_frames", "[", "'tcp'", "]", "=", "sel...
Sets activeTCP frame according to title of desired peg frame (tip, middle, etc.).
[ "Sets", "activeTCP", "frame", "according", "to", "title", "of", "desired", "peg", "frame", "(", "tip", "middle", "etc", ".", ")", "." ]
[ "\"\"\"Sets activeTCP frame according to title of desired peg frame (tip, middle, etc.). This frame must be included in the YAML.\n :param tool_name: (string) Key in tool_data dictionary for desired frame.\n \"\"\"", "# TODO: Make this a loop-run state to slowly slerp from one TCP to another using h...
[ { "param": "self", "type": null }, { "param": "tool_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "tool_name", "type": null, "docstring": "(string) Key in tool_data d...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
spiral_search_motion
<not_specific>
def spiral_search_motion(self, frequency = .15, min_amplitude = .002, max_cycles = 62.83185): """Generates position, orientation offset vectors which describe a plane spiral about z; Adds this offset to the current approach vector to create a searching pattern. Constants come from Init; x,y vec...
Generates position, orientation offset vectors which describe a plane spiral about z; Adds this offset to the current approach vector to create a searching pattern. Constants come from Init; x,y vector currently comes from x_ and y_pos_offset variables.
Generates position, orientation offset vectors which describe a plane spiral about z; Adds this offset to the current approach vector to create a searching pattern. Constants come from Init; x,y vector currently comes from x_ and y_pos_offset variables.
[ "Generates", "position", "orientation", "offset", "vectors", "which", "describe", "a", "plane", "spiral", "about", "z", ";", "Adds", "this", "offset", "to", "the", "current", "approach", "vector", "to", "create", "a", "searching", "pattern", ".", "Constants", ...
def spiral_search_motion(self, frequency = .15, min_amplitude = .002, max_cycles = 62.83185): curr_time = rospy.get_rostime() - self._start_time curr_time_numpy = np.double(curr_time.to_sec()) curr_amp = min_amplitude + self.safe_clearance * np.mod(2.0 * np.pi * frequency *curr_time_numpy, max_c...
[ "def", "spiral_search_motion", "(", "self", ",", "frequency", "=", ".15", ",", "min_amplitude", "=", ".002", ",", "max_cycles", "=", "62.83185", ")", ":", "curr_time", "=", "rospy", ".", "get_rostime", "(", ")", "-", "self", ".", "_start_time", "curr_time_nu...
Generates position, orientation offset vectors which describe a plane spiral about z; Adds this offset to the current approach vector to create a searching pattern.
[ "Generates", "position", "orientation", "offset", "vectors", "which", "describe", "a", "plane", "spiral", "about", "z", ";", "Adds", "this", "offset", "to", "the", "current", "approach", "vector", "to", "create", "a", "searching", "pattern", "." ]
[ "\"\"\"Generates position, orientation offset vectors which describe a plane spiral about z; \n Adds this offset to the current approach vector to create a searching pattern. Constants come from Init;\n x,y vector currently comes from x_ and y_pos_offset variables.\n \"\"\"", "#0.104 is the a...
[ { "param": "self", "type": null }, { "param": "frequency", "type": null }, { "param": "min_amplitude", "type": null }, { "param": "max_cycles", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "frequency", "type": null, "docstring": null, "docstring_token...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
linear_search_position
<not_specific>
def linear_search_position(self, direction_vector = [0,0,0], desired_orientation = [0, 1, 0, 0]): """Generates a command pose vector which causes the robot to hold a certain orientation and comply in z while maintaining the approach vector along x_ and y_pos_offset. :param direction_vector: (li...
Generates a command pose vector which causes the robot to hold a certain orientation and comply in z while maintaining the approach vector along x_ and y_pos_offset. :param direction_vector: (list of floats) vector directional offset from normal position. Causes constant motion in z. :param des...
Generates a command pose vector which causes the robot to hold a certain orientation and comply in z while maintaining the approach vector along x_ and y_pos_offset.
[ "Generates", "a", "command", "pose", "vector", "which", "causes", "the", "robot", "to", "hold", "a", "certain", "orientation", "and", "comply", "in", "z", "while", "maintaining", "the", "approach", "vector", "along", "x_", "and", "y_pos_offset", "." ]
def linear_search_position(self, direction_vector = [0,0,0], desired_orientation = [0, 1, 0, 0]): pose_position = self.current_pose.transform.translation pose_position.x = self.x_pos_offset + direction_vector[0] pose_position.y = self.y_pos_offset + direction_vector[1] pose_position.z = ...
[ "def", "linear_search_position", "(", "self", ",", "direction_vector", "=", "[", "0", ",", "0", ",", "0", "]", ",", "desired_orientation", "=", "[", "0", ",", "1", ",", "0", ",", "0", "]", ")", ":", "pose_position", "=", "self", ".", "current_pose", ...
Generates a command pose vector which causes the robot to hold a certain orientation and comply in z while maintaining the approach vector along x_ and y_pos_offset.
[ "Generates", "a", "command", "pose", "vector", "which", "causes", "the", "robot", "to", "hold", "a", "certain", "orientation", "and", "comply", "in", "z", "while", "maintaining", "the", "approach", "vector", "along", "x_", "and", "y_pos_offset", "." ]
[ "\"\"\"Generates a command pose vector which causes the robot to hold a certain orientation\n and comply in z while maintaining the approach vector along x_ and y_pos_offset.\n :param direction_vector: (list of floats) vector directional offset from normal position. Causes constant motion in z.\n ...
[ { "param": "self", "type": null }, { "param": "direction_vector", "type": null }, { "param": "desired_orientation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "direction_vector", "type": null, "docstring": "(list of floats) vec...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
full_compliance_position
<not_specific>
def full_compliance_position(self, direction_vector = [0,0,0], desired_orientation = [0, 1, 0, 0]): """Generates a command pose vector which causes the robot to hold a certain orientation and comply translationally in all directions. :param direction_vector: (list of floats) vector directional ...
Generates a command pose vector which causes the robot to hold a certain orientation and comply translationally in all directions. :param direction_vector: (list of floats) vector directional offset from normal position. Causes constant motion. :param desired_orientation: (list of floats) quate...
Generates a command pose vector which causes the robot to hold a certain orientation and comply translationally in all directions.
[ "Generates", "a", "command", "pose", "vector", "which", "causes", "the", "robot", "to", "hold", "a", "certain", "orientation", "and", "comply", "translationally", "in", "all", "directions", "." ]
def full_compliance_position(self, direction_vector = [0,0,0], desired_orientation = [0, 1, 0, 0]): pose_position = self.current_pose.transform.translation pose_position.x = pose_position.x + direction_vector[0] pose_position.y = pose_position.y + direction_vector[1] pose_position.z = po...
[ "def", "full_compliance_position", "(", "self", ",", "direction_vector", "=", "[", "0", ",", "0", ",", "0", "]", ",", "desired_orientation", "=", "[", "0", ",", "1", ",", "0", ",", "0", "]", ")", ":", "pose_position", "=", "self", ".", "current_pose", ...
Generates a command pose vector which causes the robot to hold a certain orientation and comply translationally in all directions.
[ "Generates", "a", "command", "pose", "vector", "which", "causes", "the", "robot", "to", "hold", "a", "certain", "orientation", "and", "comply", "translationally", "in", "all", "directions", "." ]
[ "\"\"\"Generates a command pose vector which causes the robot to hold a certain orientation\n and comply translationally in all directions.\n :param direction_vector: (list of floats) vector directional offset from normal position. Causes constant motion.\n :param desired_orientation: (list of...
[ { "param": "self", "type": null }, { "param": "direction_vector", "type": null }, { "param": "desired_orientation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "direction_vector", "type": null, "docstring": "(list of floats) vec...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
callback_update_wrench
null
def callback_update_wrench(self, data: WrenchStamped): """Callback to update current wrench data whenever new data becomes available. """ self.current_wrench = data # rospy.loginfo_once("Callback working! " + str(data))
Callback to update current wrench data whenever new data becomes available.
Callback to update current wrench data whenever new data becomes available.
[ "Callback", "to", "update", "current", "wrench", "data", "whenever", "new", "data", "becomes", "available", "." ]
def callback_update_wrench(self, data: WrenchStamped): self.current_wrench = data
[ "def", "callback_update_wrench", "(", "self", ",", "data", ":", "WrenchStamped", ")", ":", "self", ".", "current_wrench", "=", "data" ]
Callback to update current wrench data whenever new data becomes available.
[ "Callback", "to", "update", "current", "wrench", "data", "whenever", "new", "data", "becomes", "available", "." ]
[ "\"\"\"Callback to update current wrench data whenever new data becomes available.\n \"\"\"", "# rospy.loginfo_once(\"Callback working! \" + str(data))" ]
[ { "param": "self", "type": null }, { "param": "data", "type": "WrenchStamped" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": "WrenchStamped", "docstring": null, "docstring...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
publish_wrench
null
def publish_wrench(self, input_vec): """Publish the commanded wrench to the command topic. :param vec: (list of Floats) XYZ force commands :param vec: (list of Floats) XYC commanded torque. """ # self.check_controller(self.force_controller) # forces, torques = self.com_to...
Publish the commanded wrench to the command topic. :param vec: (list of Floats) XYZ force commands :param vec: (list of Floats) XYC commanded torque.
Publish the commanded wrench to the command topic.
[ "Publish", "the", "commanded", "wrench", "to", "the", "command", "topic", "." ]
def publish_wrench(self, input_vec): result_wrench = self.create_wrench(input_vec[:3], input_vec[3:]) transform_world_to_gripper:TransformStamped = self.tf_buffer.lookup_transform('target_hole_position', 'tool0', rospy.Time(0), rospy.Duration(1.25)) offset =Point( -1*self.tool_data[self.activeTC...
[ "def", "publish_wrench", "(", "self", ",", "input_vec", ")", ":", "result_wrench", "=", "self", ".", "create_wrench", "(", "input_vec", "[", ":", "3", "]", ",", "input_vec", "[", "3", ":", "]", ")", "transform_world_to_gripper", ":", "TransformStamped", "=",...
Publish the commanded wrench to the command topic.
[ "Publish", "the", "commanded", "wrench", "to", "the", "command", "topic", "." ]
[ "\"\"\"Publish the commanded wrench to the command topic.\n :param vec: (list of Floats) XYZ force commands\n :param vec: (list of Floats) XYC commanded torque.\n \"\"\"", "# self.check_controller(self.force_controller)", "# forces, torques = self.com_to_tcp(result[:3], result[3:], transfor...
[ { "param": "self", "type": null }, { "param": "input_vec", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "input_vec", "type": null, "docstring": null, "docstring_token...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
publish_pose
null
def publish_pose(self, pose_stamped_vec): """Takes in vector representations of position :param pose_stamped_vec: (list of floats) List of parameters for pose with x,y,z position and orientation quaternion """ # Ensure controller is loaded # self.check_controller(self.controller...
Takes in vector representations of position :param pose_stamped_vec: (list of floats) List of parameters for pose with x,y,z position and orientation quaternion
Takes in vector representations of position
[ "Takes", "in", "vector", "representations", "of", "position" ]
def publish_pose(self, pose_stamped_vec): goal_pose = PoseStamped() point = Point() quaternion = Quaternion() point.x, point.y, point.z = pose_stamped_vec[0][:] goal_pose.pose.position = point quaternion.w, quaternion.x, quaternion.y, quaternion.z = pose_stamped_vec[1][:...
[ "def", "publish_pose", "(", "self", ",", "pose_stamped_vec", ")", ":", "goal_pose", "=", "PoseStamped", "(", ")", "point", "=", "Point", "(", ")", "quaternion", "=", "Quaternion", "(", ")", "point", ".", "x", ",", "point", ".", "y", ",", "point", ".", ...
Takes in vector representations of position
[ "Takes", "in", "vector", "representations", "of", "position" ]
[ "\"\"\"Takes in vector representations of position \n :param pose_stamped_vec: (list of floats) List of parameters for pose with x,y,z position and orientation quaternion\n \"\"\"", "# Ensure controller is loaded", "# self.check_controller(self.controller_name)", "# Create poseStamped msg", "#...
[ { "param": "self", "type": null }, { "param": "pose_stamped_vec", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose_stamped_vec", "type": null, "docstring": "(list of floats) Lis...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
to_homogeneous
<not_specific>
def to_homogeneous(quat, point): """Takes a quaternion and msg.Point and outputs a homog. tf matrix. :param quat: (geometry_msgs.Quaternion) Orientation information. :param point: (geometry.msgs.Point) Position information. :return: (np.Array()) 4x4 Homogeneous transform matrix. ...
Takes a quaternion and msg.Point and outputs a homog. tf matrix. :param quat: (geometry_msgs.Quaternion) Orientation information. :param point: (geometry.msgs.Point) Position information. :return: (np.Array()) 4x4 Homogeneous transform matrix.
Takes a quaternion and msg.Point and outputs a homog. tf matrix.
[ "Takes", "a", "quaternion", "and", "msg", ".", "Point", "and", "outputs", "a", "homog", ".", "tf", "matrix", "." ]
def to_homogeneous(quat, point): output = trfm.quaternion_matrix(np.array([quat.x, quat.y, quat.z, quat.w])) output[0][3] = point.x output[1][3] = point.y output[2][3] = point.z return output
[ "def", "to_homogeneous", "(", "quat", ",", "point", ")", ":", "output", "=", "trfm", ".", "quaternion_matrix", "(", "np", ".", "array", "(", "[", "quat", ".", "x", ",", "quat", ".", "y", ",", "quat", ".", "z", ",", "quat", ".", "w", "]", ")", "...
Takes a quaternion and msg.Point and outputs a homog.
[ "Takes", "a", "quaternion", "and", "msg", ".", "Point", "and", "outputs", "a", "homog", "." ]
[ "\"\"\"Takes a quaternion and msg.Point and outputs a homog. tf matrix.\n :param quat: (geometry_msgs.Quaternion) Orientation information.\n :param point: (geometry.msgs.Point) Position information.\n :return: (np.Array()) 4x4 Homogeneous transform matrix.\n \"\"\"", "#TODO candidate f...
[ { "param": "quat", "type": null }, { "param": "point", "type": null } ]
{ "returns": [ { "docstring": "(np.Array()) 4x4 Homogeneous transform matrix.", "docstring_tokens": [ "(", "np", ".", "Array", "()", ")", "4x4", "Homogeneous", "transform", "matrix", "." ], "type": null...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
matrix_to_pose
<not_specific>
def matrix_to_pose(input, base_frame): """Converts matrix into a pose. :param input: (np.Array) 4x4 homogeneous transformation matrix :param base_frame: (string) base frame for new pose. :return: (geometry_msgs.PoseStamped) Pose based on input. """ output = PoseStamped() ...
Converts matrix into a pose. :param input: (np.Array) 4x4 homogeneous transformation matrix :param base_frame: (string) base frame for new pose. :return: (geometry_msgs.PoseStamped) Pose based on input.
Converts matrix into a pose.
[ "Converts", "matrix", "into", "a", "pose", "." ]
def matrix_to_pose(input, base_frame): output = PoseStamped() output.header.stamp = rospy.get_rostime() output.header.frame_id = base_frame quat = trfm.quaternion_from_matrix(input) output.pose.orientation.x = quat[0] output.pose.orientation.y = quat[1] output.pos...
[ "def", "matrix_to_pose", "(", "input", ",", "base_frame", ")", ":", "output", "=", "PoseStamped", "(", ")", "output", ".", "header", ".", "stamp", "=", "rospy", ".", "get_rostime", "(", ")", "output", ".", "header", ".", "frame_id", "=", "base_frame", "q...
Converts matrix into a pose.
[ "Converts", "matrix", "into", "a", "pose", "." ]
[ "\"\"\"Converts matrix into a pose.\n :param input: (np.Array) 4x4 homogeneous transformation matrix\n :param base_frame: (string) base frame for new pose.\n :return: (geometry_msgs.PoseStamped) Pose based on input.\n \"\"\"" ]
[ { "param": "input", "type": null }, { "param": "base_frame", "type": null } ]
{ "returns": [ { "docstring": "(geometry_msgs.PoseStamped) Pose based on input.", "docstring_tokens": [ "(", "geometry_msgs", ".", "PoseStamped", ")", "Pose", "based", "on", "input", "." ], "type": null } ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
create_adjoint_representation
<not_specific>
def create_adjoint_representation(T_ab=None, R_ab=None, P_ab=None): """Convert homogeneous transform (T_ab) or a combination rotation matrix (R_ab) and pose (P_ab) into the adjoint representation. This can be used to transform wrenches (e.g., force and torque) between frames. If T_ab is provide...
Convert homogeneous transform (T_ab) or a combination rotation matrix (R_ab) and pose (P_ab) into the adjoint representation. This can be used to transform wrenches (e.g., force and torque) between frames. If T_ab is provided, R_ab and P_ab will be ignored. :param T_ab: (np.Array) 4x4 homogeneo...
Convert homogeneous transform (T_ab) or a combination rotation matrix (R_ab) and pose (P_ab) into the adjoint representation. This can be used to transform wrenches between frames. If T_ab is provided, R_ab and P_ab will be ignored.
[ "Convert", "homogeneous", "transform", "(", "T_ab", ")", "or", "a", "combination", "rotation", "matrix", "(", "R_ab", ")", "and", "pose", "(", "P_ab", ")", "into", "the", "adjoint", "representation", ".", "This", "can", "be", "used", "to", "transform", "wr...
def create_adjoint_representation(T_ab=None, R_ab=None, P_ab=None): if (type(T_ab) == type(None)): T_ab = RpToTrans(R_ab, P_ab) Ad_T = homogeneous_to_adjoint(T_ab) return Ad_T
[ "def", "create_adjoint_representation", "(", "T_ab", "=", "None", ",", "R_ab", "=", "None", ",", "P_ab", "=", "None", ")", ":", "if", "(", "type", "(", "T_ab", ")", "==", "type", "(", "None", ")", ")", ":", "T_ab", "=", "RpToTrans", "(", "R_ab", ",...
Convert homogeneous transform (T_ab) or a combination rotation matrix (R_ab) and pose (P_ab) into the adjoint representation.
[ "Convert", "homogeneous", "transform", "(", "T_ab", ")", "or", "a", "combination", "rotation", "matrix", "(", "R_ab", ")", "and", "pose", "(", "P_ab", ")", "into", "the", "adjoint", "representation", "." ]
[ "\"\"\"Convert homogeneous transform (T_ab) or a combination rotation matrix (R_ab) and pose (P_ab) \n into the adjoint representation. This can be used to transform wrenches (e.g., force and torque) between frames.\n If T_ab is provided, R_ab and P_ab will be ignored.\n :param T_ab: (np.Array)...
[ { "param": "T_ab", "type": null }, { "param": "R_ab", "type": null }, { "param": "P_ab", "type": null } ]
{ "returns": [ { "docstring": "(np.Array) 6x6 adjoint representation of the transformation", "docstring_tokens": [ "(", "np", ".", "Array", ")", "6x6", "adjoint", "representation", "of", "the", "transformation" ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
wrenchToArray
<not_specific>
def wrenchToArray(wrench: Wrench): """Restructures wrench object into numpy array with order needed by wrench reinterpretation math, namely, torque first then forces. :param wrench: (geometry_msgs.Wrench) Input wrench. :return: (np.Array) 1x6 numpy array """ return np.array([wre...
Restructures wrench object into numpy array with order needed by wrench reinterpretation math, namely, torque first then forces. :param wrench: (geometry_msgs.Wrench) Input wrench. :return: (np.Array) 1x6 numpy array
Restructures wrench object into numpy array with order needed by wrench reinterpretation math, namely, torque first then forces.
[ "Restructures", "wrench", "object", "into", "numpy", "array", "with", "order", "needed", "by", "wrench", "reinterpretation", "math", "namely", "torque", "first", "then", "forces", "." ]
def wrenchToArray(wrench: Wrench): return np.array([wrench.torque.x, wrench.torque.y, wrench.torque.z, wrench.force.x, wrench.force.y, wrench.force.z])
[ "def", "wrenchToArray", "(", "wrench", ":", "Wrench", ")", ":", "return", "np", ".", "array", "(", "[", "wrench", ".", "torque", ".", "x", ",", "wrench", ".", "torque", ".", "y", ",", "wrench", ".", "torque", ".", "z", ",", "wrench", ".", "force", ...
Restructures wrench object into numpy array with order needed by wrench reinterpretation math, namely, torque first then forces.
[ "Restructures", "wrench", "object", "into", "numpy", "array", "with", "order", "needed", "by", "wrench", "reinterpretation", "math", "namely", "torque", "first", "then", "forces", "." ]
[ "\"\"\"Restructures wrench object into numpy array with order needed by wrench reinterpretation math, namely, torque first then forces.\n :param wrench: (geometry_msgs.Wrench) Input wrench.\n :return: (np.Array) 1x6 numpy array \n \"\"\"" ]
[ { "param": "wrench", "type": "Wrench" } ]
{ "returns": [ { "docstring": "(np.Array) 1x6 numpy array", "docstring_tokens": [ "(", "np", ".", "Array", ")", "1x6", "numpy", "array" ], "type": null } ], "raises": [], "params": [ { "identifier": "wrench...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
arrayToWrench
np.ndarray
def arrayToWrench(array: np.ndarray) -> np.ndarray: """Restructures output 1x6 mathematical array representation of a wrench into a wrench object. :param wrench: (np.Array) 1x6 numpy array :return: (geometry_msgs.Wrench) Return wrench. """ return Wrench(Point(*list(array[3:])),...
Restructures output 1x6 mathematical array representation of a wrench into a wrench object. :param wrench: (np.Array) 1x6 numpy array :return: (geometry_msgs.Wrench) Return wrench.
Restructures output 1x6 mathematical array representation of a wrench into a wrench object.
[ "Restructures", "output", "1x6", "mathematical", "array", "representation", "of", "a", "wrench", "into", "a", "wrench", "object", "." ]
def arrayToWrench(array: np.ndarray) -> np.ndarray: return Wrench(Point(*list(array[3:])), Point(*list(array[:3])))
[ "def", "arrayToWrench", "(", "array", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "return", "Wrench", "(", "Point", "(", "*", "list", "(", "array", "[", "3", ":", "]", ")", ")", ",", "Point", "(", "*", "list", "(", "array", ...
Restructures output 1x6 mathematical array representation of a wrench into a wrench object.
[ "Restructures", "output", "1x6", "mathematical", "array", "representation", "of", "a", "wrench", "into", "a", "wrench", "object", "." ]
[ "\"\"\"Restructures output 1x6 mathematical array representation of a wrench into a wrench object.\n :param wrench: (np.Array) 1x6 numpy array \n :return: (geometry_msgs.Wrench) Return wrench.\n \"\"\"" ]
[ { "param": "array", "type": "np.ndarray" } ]
{ "returns": [ { "docstring": "(geometry_msgs.Wrench) Return wrench.", "docstring_tokens": [ "(", "geometry_msgs", ".", "Wrench", ")", "Return", "wrench", "." ], "type": null } ], "raises": [], "params": [ { ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
transform_wrench
np.ndarray
def transform_wrench(transform: TransformStamped, wrench: Wrench, invert:bool=False, log:bool=False) -> np.ndarray: """Transform a wrench object by the given transform object. :param transform: (geometry_msgs.TransformStamped) Transform to apply :param wrench: (geometry_msgs.Wrench) Wrench objec...
Transform a wrench object by the given transform object. :param transform: (geometry_msgs.TransformStamped) Transform to apply :param wrench: (geometry_msgs.Wrench) Wrench object to transform. :param invert: (bool) Whether to interpret the tansformation's inverse, i.e. transform "from child to p...
Transform a wrench object by the given transform object.
[ "Transform", "a", "wrench", "object", "by", "the", "given", "transform", "object", "." ]
def transform_wrench(transform: TransformStamped, wrench: Wrench, invert:bool=False, log:bool=False) -> np.ndarray: matrix = AssemblyTools.to_homogeneous(transform.transform.rotation, transform.transform.translation) if(log): rospy.loginfo_throttle(2, Fore.RED + " Transform passed in is " + ...
[ "def", "transform_wrench", "(", "transform", ":", "TransformStamped", ",", "wrench", ":", "Wrench", ",", "invert", ":", "bool", "=", "False", ",", "log", ":", "bool", "=", "False", ")", "->", "np", ".", "ndarray", ":", "matrix", "=", "AssemblyTools", "."...
Transform a wrench object by the given transform object.
[ "Transform", "a", "wrench", "object", "by", "the", "given", "transform", "object", "." ]
[ "\"\"\"Transform a wrench object by the given transform object.\n :param transform: (geometry_msgs.TransformStamped) Transform to apply\n :param wrench: (geometry_msgs.Wrench) Wrench object to transform.\n :param invert: (bool) Whether to interpret the tansformation's inverse, i.e. transform \"...
[ { "param": "transform", "type": "TransformStamped" }, { "param": "wrench", "type": "Wrench" }, { "param": "invert", "type": "bool" }, { "param": "log", "type": "bool" } ]
{ "returns": [ { "docstring": "(geometry.msgs.Wrench) changed wrench", "docstring_tokens": [ "(", "geometry", ".", "msgs", ".", "Wrench", ")", "changed", "wrench" ], "type": null } ], "raises": [], "params": ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
transform_wrench_by_matrix
np.ndarray
def transform_wrench_by_matrix(T_ab:np.ndarray, wrench:np.ndarray) -> np.ndarray: """Use the homogeneous transform (T_ab) to transform a given wrench using an adjoint transformation (see create_adjoint_representation). :param T_ab: (np.Array) 4x4 homogeneous transformation matrix representing frame 'b' ...
Use the homogeneous transform (T_ab) to transform a given wrench using an adjoint transformation (see create_adjoint_representation). :param T_ab: (np.Array) 4x4 homogeneous transformation matrix representing frame 'b' relative to frame 'a' :param wrench: (np.Array) 6x1 representation of a wrench relati...
Use the homogeneous transform (T_ab) to transform a given wrench using an adjoint transformation .
[ "Use", "the", "homogeneous", "transform", "(", "T_ab", ")", "to", "transform", "a", "given", "wrench", "using", "an", "adjoint", "transformation", "." ]
def transform_wrench_by_matrix(T_ab:np.ndarray, wrench:np.ndarray) -> np.ndarray: Ad_T = AssemblyTools.create_adjoint_representation(T_ab) wrench_transformed = np.matmul(Ad_T.T, wrench) return AssemblyTools.arrayToWrench(wrench_transformed)
[ "def", "transform_wrench_by_matrix", "(", "T_ab", ":", "np", ".", "ndarray", ",", "wrench", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "Ad_T", "=", "AssemblyTools", ".", "create_adjoint_representation", "(", "T_ab", ")", "wrench_transform...
Use the homogeneous transform (T_ab) to transform a given wrench using an adjoint transformation (see create_adjoint_representation).
[ "Use", "the", "homogeneous", "transform", "(", "T_ab", ")", "to", "transform", "a", "given", "wrench", "using", "an", "adjoint", "transformation", "(", "see", "create_adjoint_representation", ")", "." ]
[ "\"\"\"Use the homogeneous transform (T_ab) to transform a given wrench using an adjoint transformation (see create_adjoint_representation).\n :param T_ab: (np.Array) 4x4 homogeneous transformation matrix representing frame 'b' relative to frame 'a'\n :param wrench: (np.Array) 6x1 representation of a ...
[ { "param": "T_ab", "type": "np.ndarray" }, { "param": "wrench", "type": "np.ndarray" } ]
{ "returns": [ { "docstring": "(np.Array) 6x1 representation of a wrench relative to frame 'b'. This should include forces and torques as np.array([torque, force])", "docstring_tokens": [ "(", "np", ".", "Array", ")", "6x1", "representation", ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
matrix_to_tf
<not_specific>
def matrix_to_tf(input:np.ndarray, base_frame:String, child_frame:String): """Converts matrix back into a TF. :param input: (np.Array) 4x4 homogeneous transformation matrix :param base_frame: (string) base frame for new pose. :return: (geometry_msgs.TransformStamped) Transform based on i...
Converts matrix back into a TF. :param input: (np.Array) 4x4 homogeneous transformation matrix :param base_frame: (string) base frame for new pose. :return: (geometry_msgs.TransformStamped) Transform based on input.
Converts matrix back into a TF.
[ "Converts", "matrix", "back", "into", "a", "TF", "." ]
def matrix_to_tf(input:np.ndarray, base_frame:String, child_frame:String): pose = AssemblyTools.matrix_to_pose(input, base_frame) output = AssemblyTools.swap_pose_tf(pose, child_frame) return output
[ "def", "matrix_to_tf", "(", "input", ":", "np", ".", "ndarray", ",", "base_frame", ":", "String", ",", "child_frame", ":", "String", ")", ":", "pose", "=", "AssemblyTools", ".", "matrix_to_pose", "(", "input", ",", "base_frame", ")", "output", "=", "Assemb...
Converts matrix back into a TF.
[ "Converts", "matrix", "back", "into", "a", "TF", "." ]
[ "\"\"\"Converts matrix back into a TF.\n :param input: (np.Array) 4x4 homogeneous transformation matrix\n :param base_frame: (string) base frame for new pose.\n :return: (geometry_msgs.TransformStamped) Transform based on input.\n \"\"\"" ]
[ { "param": "input", "type": "np.ndarray" }, { "param": "base_frame", "type": "String" }, { "param": "child_frame", "type": "String" } ]
{ "returns": [ { "docstring": "(geometry_msgs.TransformStamped) Transform based on input.", "docstring_tokens": [ "(", "geometry_msgs", ".", "TransformStamped", ")", "Transform", "based", "on", "input", "." ], ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
swap_pose_tf
TransformStamped
def swap_pose_tf(input:PoseStamped, child_frame:String) -> TransformStamped: """Swaps pose for tf and vice-versa. :param input: (geometry_msgs.PoseStamped or geometry_msgs.TransformStamped) Input data type. :param child_frame: (string) Child frame name if converting Pose to Transform. :r...
Swaps pose for tf and vice-versa. :param input: (geometry_msgs.PoseStamped or geometry_msgs.TransformStamped) Input data type. :param child_frame: (string) Child frame name if converting Pose to Transform. :return: (geometry_msgs.TransformStamped or geometry_msgs.PoseStamped) Output data, of the...
Swaps pose for tf and vice-versa.
[ "Swaps", "pose", "for", "tf", "and", "vice", "-", "versa", "." ]
def swap_pose_tf(input:PoseStamped, child_frame:String) -> TransformStamped: if('PoseStamped' in str(type(input))): output = TransformStamped() output.header = input.header [output.transform.translation.x, output.transform.translation.y, output.transform.translation.z] = [inp...
[ "def", "swap_pose_tf", "(", "input", ":", "PoseStamped", ",", "child_frame", ":", "String", ")", "->", "TransformStamped", ":", "if", "(", "'PoseStamped'", "in", "str", "(", "type", "(", "input", ")", ")", ")", ":", "output", "=", "TransformStamped", "(", ...
Swaps pose for tf and vice-versa.
[ "Swaps", "pose", "for", "tf", "and", "vice", "-", "versa", "." ]
[ "\"\"\"Swaps pose for tf and vice-versa.\n :param input: (geometry_msgs.PoseStamped or geometry_msgs.TransformStamped) Input data type.\n :param child_frame: (string) Child frame name if converting Pose to Transform.\n :return: (geometry_msgs.TransformStamped or geometry_msgs.PoseStamped) Outpu...
[ { "param": "input", "type": "PoseStamped" }, { "param": "child_frame", "type": "String" } ]
{ "returns": [ { "docstring": "(geometry_msgs.TransformStamped or geometry_msgs.PoseStamped) Output data, of the other type from input.", "docstring_tokens": [ "(", "geometry_msgs", ".", "TransformStamped", "or", "geometry_msgs", ".", "Po...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
create_wrench
WrenchStamped
def create_wrench(self, force:list, torque:list) -> WrenchStamped: """Composes a standard wrench object from human-readable vectors. :param force: (list of floats) x,y,z force values :param torque: (list of floats) torques about x,y,z :return: (geometry.msgs.WrenchStamped) Output wrench....
Composes a standard wrench object from human-readable vectors. :param force: (list of floats) x,y,z force values :param torque: (list of floats) torques about x,y,z :return: (geometry.msgs.WrenchStamped) Output wrench.
Composes a standard wrench object from human-readable vectors.
[ "Composes", "a", "standard", "wrench", "object", "from", "human", "-", "readable", "vectors", "." ]
def create_wrench(self, force:list, torque:list) -> WrenchStamped: wrench_stamped = WrenchStamped() wrench = Wrench() wrench.force.x, wrench.force.y, wrench.force.z = force wrench.torque.x, wrench.torque.y, wrench.torque.z = torque wrench_stamped.header.stamp = rospy.get_rostime...
[ "def", "create_wrench", "(", "self", ",", "force", ":", "list", ",", "torque", ":", "list", ")", "->", "WrenchStamped", ":", "wrench_stamped", "=", "WrenchStamped", "(", ")", "wrench", "=", "Wrench", "(", ")", "wrench", ".", "force", ".", "x", ",", "wr...
Composes a standard wrench object from human-readable vectors.
[ "Composes", "a", "standard", "wrench", "object", "from", "human", "-", "readable", "vectors", "." ]
[ "\"\"\"Composes a standard wrench object from human-readable vectors.\n :param force: (list of floats) x,y,z force values\n :param torque: (list of floats) torques about x,y,z\n :return: (geometry.msgs.WrenchStamped) Output wrench.\n \"\"\"", "# create wrench", "# create header", "...
[ { "param": "self", "type": null }, { "param": "force", "type": "list" }, { "param": "torque", "type": "list" } ]
{ "returns": [ { "docstring": "(geometry.msgs.WrenchStamped) Output wrench.", "docstring_tokens": [ "(", "geometry", ".", "msgs", ".", "WrenchStamped", ")", "Output", "wrench", "." ], "type": null } ], ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
update_average_wrench
None
def update_average_wrench(self) -> None: """Create a very simple moving average of the incoming wrench readings and store it as self.average.wrench. """ self._average_wrench_gripper = self.filters.average_wrench(self.current_wrench.wrench) #Get current angle from gripper to ho...
Create a very simple moving average of the incoming wrench readings and store it as self.average.wrench.
Create a very simple moving average of the incoming wrench readings and store it as self.average.wrench.
[ "Create", "a", "very", "simple", "moving", "average", "of", "the", "incoming", "wrench", "readings", "and", "store", "it", "as", "self", ".", "average", ".", "wrench", "." ]
def update_average_wrench(self) -> None: self._average_wrench_gripper = self.filters.average_wrench(self.current_wrench.wrench) transform_world_rotation:TransformStamped = self.tf_buffer.lookup_transform('tool0', 'target_hole_position', rospy.Time(0), rospy.Duration(1.25)) offset =Point(self.too...
[ "def", "update_average_wrench", "(", "self", ")", "->", "None", ":", "self", ".", "_average_wrench_gripper", "=", "self", ".", "filters", ".", "average_wrench", "(", "self", ".", "current_wrench", ".", "wrench", ")", "transform_world_rotation", ":", "TransformStam...
Create a very simple moving average of the incoming wrench readings and store it as self.average.wrench.
[ "Create", "a", "very", "simple", "moving", "average", "of", "the", "incoming", "wrench", "readings", "and", "store", "it", "as", "self", ".", "average", ".", "wrench", "." ]
[ "\"\"\"Create a very simple moving average of the incoming wrench readings and store it as self.average.wrench.\n \"\"\"", "#Get current angle from gripper to hole:", "#We want to rotate this only, not reinterpret F/T components.", "#We reinterpret based on the position of the TCP (but ignore the relat...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
update_avg_speed
None
def update_avg_speed(self) -> None: """Updates a simple moving average of robot tcp speed in mm/s. A speed is calculated from the difference between a previous pose (.1 s in the past) and the current pose; this speed is filtered and stored as self.average_speed. """ curr_time = rospy.ge...
Updates a simple moving average of robot tcp speed in mm/s. A speed is calculated from the difference between a previous pose (.1 s in the past) and the current pose; this speed is filtered and stored as self.average_speed.
Updates a simple moving average of robot tcp speed in mm/s. A speed is calculated from the difference between a previous pose (.1 s in the past) and the current pose; this speed is filtered and stored as self.average_speed.
[ "Updates", "a", "simple", "moving", "average", "of", "robot", "tcp", "speed", "in", "mm", "/", "s", ".", "A", "speed", "is", "calculated", "from", "the", "difference", "between", "a", "previous", "pose", "(", ".", "1", "s", "in", "the", "past", ")", ...
def update_avg_speed(self) -> None: curr_time = rospy.get_rostime() - self._start_time if(curr_time.to_sec() > rospy.Duration(.5).to_sec()): try: earlierPosition = self.tf_buffer.lookup_transform("base_link", self.tool_data[self.activeTCP]['transform'].child_frame_id, ...
[ "def", "update_avg_speed", "(", "self", ")", "->", "None", ":", "curr_time", "=", "rospy", ".", "get_rostime", "(", ")", "-", "self", ".", "_start_time", "if", "(", "curr_time", ".", "to_sec", "(", ")", ">", "rospy", ".", "Duration", "(", ".5", ")", ...
Updates a simple moving average of robot tcp speed in mm/s.
[ "Updates", "a", "simple", "moving", "average", "of", "robot", "tcp", "speed", "in", "mm", "/", "s", "." ]
[ "\"\"\"Updates a simple moving average of robot tcp speed in mm/s. A speed is calculated from the difference between a\n previous pose (.1 s in the past) and the current pose; this speed is filtered and stored as self.average_speed.\n \"\"\"", "#Speed Diff: distance moved / time between poses", "...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
publish_plotted_values
None
def publish_plotted_values(self) -> None: """Publishes critical data for plotting node to process. """ self.avg_wrench_pub.publish(self._average_wrench_world) self.avg_speed_pub.publish(Point(self.average_speed[0], self.average_speed[1],self.average_speed[2])) self.rel_position...
Publishes critical data for plotting node to process.
Publishes critical data for plotting node to process.
[ "Publishes", "critical", "data", "for", "plotting", "node", "to", "process", "." ]
def publish_plotted_values(self) -> None: self.avg_wrench_pub.publish(self._average_wrench_world) self.avg_speed_pub.publish(Point(self.average_speed[0], self.average_speed[1],self.average_speed[2])) self.rel_position_pub.publish(self.current_pose.transform.translation) status_dict = dic...
[ "def", "publish_plotted_values", "(", "self", ")", "->", "None", ":", "self", ".", "avg_wrench_pub", ".", "publish", "(", "self", ".", "_average_wrench_world", ")", "self", ".", "avg_speed_pub", ".", "publish", "(", "Point", "(", "self", ".", "average_speed", ...
Publishes critical data for plotting node to process.
[ "Publishes", "critical", "data", "for", "plotting", "node", "to", "process", "." ]
[ "\"\"\"Publishes critical data for plotting node to process.\n \"\"\"", "# Send a dictionary as plain text to expose some additional info", "# If we have located the work surface" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
as_array
np.ndarray
def as_array(self, vec:Point) -> np.ndarray: """Takes a Point and returns a Numpy array. :param vec: (geometry_msgs.Point) Vector in serialized ROS format. :return: (numpy.Array) Vector in 3x1 numpy array format. """ #insist that we get a 1D array returned return np.array...
Takes a Point and returns a Numpy array. :param vec: (geometry_msgs.Point) Vector in serialized ROS format. :return: (numpy.Array) Vector in 3x1 numpy array format.
Takes a Point and returns a Numpy array.
[ "Takes", "a", "Point", "and", "returns", "a", "Numpy", "array", "." ]
def as_array(self, vec:Point) -> np.ndarray: return np.array([vec.x, vec.y, vec.z]).reshape(-1,)
[ "def", "as_array", "(", "self", ",", "vec", ":", "Point", ")", "->", "np", ".", "ndarray", ":", "return", "np", ".", "array", "(", "[", "vec", ".", "x", ",", "vec", ".", "y", ",", "vec", ".", "z", "]", ")", ".", "reshape", "(", "-", "1", ",...
Takes a Point and returns a Numpy array.
[ "Takes", "a", "Point", "and", "returns", "a", "Numpy", "array", "." ]
[ "\"\"\"Takes a Point and returns a Numpy array.\n :param vec: (geometry_msgs.Point) Vector in serialized ROS format.\n :return: (numpy.Array) Vector in 3x1 numpy array format.\n \"\"\"", "#insist that we get a 1D array returned" ]
[ { "param": "self", "type": null }, { "param": "vec", "type": "Point" } ]
{ "returns": [ { "docstring": "(numpy.Array) Vector in 3x1 numpy array format.", "docstring_tokens": [ "(", "numpy", ".", "Array", ")", "Vector", "in", "3x1", "numpy", "array", "format", "." ], ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
vectorRegionCompare
bool
def vectorRegionCompare(self, input:list, bounds_max:list, bounds_min:list) -> bool: """.. vectorRegionCompare Compares an input to boundaries element-wise. Essentially checks whether a vector is within a rectangular region. :param input: (list of floats) x,y,z of a vector to check. :param bound...
.. vectorRegionCompare Compares an input to boundaries element-wise. Essentially checks whether a vector is within a rectangular region. :param input: (list of floats) x,y,z of a vector to check. :param bounds_max: (list of floats) x,y,z max value of each element. :param bounds_min: (list of flo...
vectorRegionCompare Compares an input to boundaries element-wise. Essentially checks whether a vector is within a rectangular region.
[ "vectorRegionCompare", "Compares", "an", "input", "to", "boundaries", "element", "-", "wise", ".", "Essentially", "checks", "whether", "a", "vector", "is", "within", "a", "rectangular", "region", "." ]
def vectorRegionCompare(self, input:list, bounds_max:list, bounds_min:list) -> bool: if( bounds_max[0] >= input[0] >= bounds_min[0]): if( bounds_max[1] >= input[1] >= bounds_min[1]): if( bounds_max[2] >= input[2] >= bounds_min[2]): return True return False
[ "def", "vectorRegionCompare", "(", "self", ",", "input", ":", "list", ",", "bounds_max", ":", "list", ",", "bounds_min", ":", "list", ")", "->", "bool", ":", "if", "(", "bounds_max", "[", "0", "]", ">=", "input", "[", "0", "]", ">=", "bounds_min", "[...
.. vectorRegionCompare Compares an input to boundaries element-wise.
[ "..", "vectorRegionCompare", "Compares", "an", "input", "to", "boundaries", "element", "-", "wise", "." ]
[ "\"\"\".. vectorRegionCompare Compares an input to boundaries element-wise. Essentially checks whether a vector is within a rectangular region.\n :param input: (list of floats) x,y,z of a vector to check.\n :param bounds_max: (list of floats) x,y,z max value of each element.\n :param bounds_min...
[ { "param": "self", "type": null }, { "param": "input", "type": "list" }, { "param": "bounds_max", "type": "list" }, { "param": "bounds_min", "type": "list" } ]
{ "returns": [ { "docstring": "(bool) Whether the vector falls within the region.", "docstring_tokens": [ "(", "bool", ")", "Whether", "the", "vector", "falls", "within", "the", "region", "." ], "type":...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
checkIfColliding
bool
def checkIfColliding(self, commandedForce:np.ndarray, deadzoneRadius:list = [4,4,3], relativeScaling:float = .1)->bool: """Checks if an equal and opposite reaction force is stopping acceleration in all directions - this would indicate there is a static obstacle in collision with the tcp. """ fo...
Checks if an equal and opposite reaction force is stopping acceleration in all directions - this would indicate there is a static obstacle in collision with the tcp.
Checks if an equal and opposite reaction force is stopping acceleration in all directions - this would indicate there is a static obstacle in collision with the tcp.
[ "Checks", "if", "an", "equal", "and", "opposite", "reaction", "force", "is", "stopping", "acceleration", "in", "all", "directions", "-", "this", "would", "indicate", "there", "is", "a", "static", "obstacle", "in", "collision", "with", "the", "tcp", "." ]
def checkIfColliding(self, commandedForce:np.ndarray, deadzoneRadius:list = [4,4,3], relativeScaling:float = .1)->bool: force = self.as_array(self._average_wrench_world.force).reshape(3) res = np.allclose(force, -1*commandedForce, atol = deadzoneRadius, rtol = relativeScaling ) return res
[ "def", "checkIfColliding", "(", "self", ",", "commandedForce", ":", "np", ".", "ndarray", ",", "deadzoneRadius", ":", "list", "=", "[", "4", ",", "4", ",", "3", "]", ",", "relativeScaling", ":", "float", "=", ".1", ")", "->", "bool", ":", "force", "=...
Checks if an equal and opposite reaction force is stopping acceleration in all directions - this would indicate there is a static obstacle in collision with the tcp.
[ "Checks", "if", "an", "equal", "and", "opposite", "reaction", "force", "is", "stopping", "acceleration", "in", "all", "directions", "-", "this", "would", "indicate", "there", "is", "a", "static", "obstacle", "in", "collision", "with", "the", "tcp", "." ]
[ "\"\"\"Checks if an equal and opposite reaction force is stopping acceleration in all directions - this would indicate there is a static obstacle in collision with the tcp.\n \"\"\"", "# rospy.loginfo_throttle(1,Fore.BLUE + \"Collision checking force \" + str(force) + \" against command \" + str(commande...
[ { "param": "self", "type": null }, { "param": "commandedForce", "type": "np.ndarray" }, { "param": "deadzoneRadius", "type": "list" }, { "param": "relativeScaling", "type": "float" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "commandedForce", "type": "np.ndarray", "docstring": null, "do...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
force_cap_check
<not_specific>
def force_cap_check(self, danger_force=[45, 45, 45], danger_transverse_force=[3.5, 3.5, 3.5], warning_force=[25, 25, 25], warning_transverse_force=[2, 2, 2]): """Checks whether any forces or torques are dangerously high. There are two levels of response: *Elevated levels of force cause this program ...
Checks whether any forces or torques are dangerously high. There are two levels of response: *Elevated levels of force cause this program to pause for 1s. If forces remain high after pause, the system will enter a freewheeling state *Dangerously high forces will kill this program im...
Checks whether any forces or torques are dangerously high. There are two levels of response: Elevated levels of force cause this program to pause for 1s. If forces remain high after pause, the system will enter a freewheeling state Dangerously high forces will kill this program immediately to prevent damage.
[ "Checks", "whether", "any", "forces", "or", "torques", "are", "dangerously", "high", ".", "There", "are", "two", "levels", "of", "response", ":", "Elevated", "levels", "of", "force", "cause", "this", "program", "to", "pause", "for", "1s", ".", "If", "force...
def force_cap_check(self, danger_force=[45, 45, 45], danger_transverse_force=[3.5, 3.5, 3.5], warning_force=[25, 25, 25], warning_transverse_force=[2, 2, 2]): radius = np.linalg.norm(self.as_array(self.tool_data[self.activeTCP]['transform'].transform.translation)) radius = max(3, radius) rospy.l...
[ "def", "force_cap_check", "(", "self", ",", "danger_force", "=", "[", "45", ",", "45", ",", "45", "]", ",", "danger_transverse_force", "=", "[", "3.5", ",", "3.5", ",", "3.5", "]", ",", "warning_force", "=", "[", "25", ",", "25", ",", "25", "]", ",...
Checks whether any forces or torques are dangerously high.
[ "Checks", "whether", "any", "forces", "or", "torques", "are", "dangerously", "high", "." ]
[ "\"\"\"Checks whether any forces or torques are dangerously high. There are two levels of response:\n *Elevated levels of force cause this program to pause for 1s. If forces remain high after pause, \n the system will enter a freewheeling state\n *Dangerously high forces will kill t...
[ { "param": "self", "type": null }, { "param": "danger_force", "type": null }, { "param": "danger_transverse_force", "type": null }, { "param": "warning_force", "type": null }, { "param": "warning_transverse_force", "type": null } ]
{ "returns": [ { "docstring": "(Bool) True if all is safe; False if a warning stop is requested.", "docstring_tokens": [ "(", "Bool", ")", "True", "if", "all", "is", "safe", ";", "False", "if", "a", ...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
average_speed
np.ndarray
def average_speed(self, input) -> np.ndarray: """Takes speed as a list of components, returns smoothed version :param input: (numpy.Array) Speed vector :return: (numpy.Array) Smoothed speed vector """ speed = self.average_threes(Point(input[0], input[1], input[2]), 'speed') ...
Takes speed as a list of components, returns smoothed version :param input: (numpy.Array) Speed vector :return: (numpy.Array) Smoothed speed vector
Takes speed as a list of components, returns smoothed version
[ "Takes", "speed", "as", "a", "list", "of", "components", "returns", "smoothed", "version" ]
def average_speed(self, input) -> np.ndarray: speed = self.average_threes(Point(input[0], input[1], input[2]), 'speed') return np.array([speed['x'], speed['y'], speed['z']])
[ "def", "average_speed", "(", "self", ",", "input", ")", "->", "np", ".", "ndarray", ":", "speed", "=", "self", ".", "average_threes", "(", "Point", "(", "input", "[", "0", "]", ",", "input", "[", "1", "]", ",", "input", "[", "2", "]", ")", ",", ...
Takes speed as a list of components, returns smoothed version
[ "Takes", "speed", "as", "a", "list", "of", "components", "returns", "smoothed", "version" ]
[ "\"\"\"Takes speed as a list of components, returns smoothed version\n :param input: (numpy.Array) Speed vector\n :return: (numpy.Array) Smoothed speed vector\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "input", "type": null } ]
{ "returns": [ { "docstring": "(numpy.Array) Smoothed speed vector", "docstring_tokens": [ "(", "numpy", ".", "Array", ")", "Smoothed", "speed", "vector" ], "type": null } ], "raises": [], "params": [ { "id...
a507b37eaf9f713292278dd30c51d6fdbc7d2c54
swri-robotics/ConnTact
src/conntact/assembly_tools.py
[ "Apache-2.0" ]
Python
average_threes
<not_specific>
def average_threes(self, input, name): """Returns the moving average of a dict of x,y,z values :param input: (geometry_msgs.msg.Point) A point with x,y,z properties :param name: (string) Name to use for buffer dictionary :return: (dict) x,y,z dictionary of the averaged values. ""...
Returns the moving average of a dict of x,y,z values :param input: (geometry_msgs.msg.Point) A point with x,y,z properties :param name: (string) Name to use for buffer dictionary :return: (dict) x,y,z dictionary of the averaged values.
Returns the moving average of a dict of x,y,z values
[ "Returns", "the", "moving", "average", "of", "a", "dict", "of", "x", "y", "z", "values" ]
def average_threes(self, input, name): vals = self.point_to_dict(input) for k, v in vals.items(): vals[k] = self.simple_moving_average(v, 15, key=name+'_'+k) return vals
[ "def", "average_threes", "(", "self", ",", "input", ",", "name", ")", ":", "vals", "=", "self", ".", "point_to_dict", "(", "input", ")", "for", "k", ",", "v", "in", "vals", ".", "items", "(", ")", ":", "vals", "[", "k", "]", "=", "self", ".", "...
Returns the moving average of a dict of x,y,z values
[ "Returns", "the", "moving", "average", "of", "a", "dict", "of", "x", "y", "z", "values" ]
[ "\"\"\"Returns the moving average of a dict of x,y,z values\n :param input: (geometry_msgs.msg.Point) A point with x,y,z properties\n :param name: (string) Name to use for buffer dictionary\n :return: (dict) x,y,z dictionary of the averaged values.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "input", "type": null }, { "param": "name", "type": null } ]
{ "returns": [ { "docstring": "(dict) x,y,z dictionary of the averaged values.", "docstring_tokens": [ "(", "dict", ")", "x", "y", "z", "dictionary", "of", "the", "averaged", "values", "." ], "t...
5214b68870ece3123bc4f5d2a4c1da7549fb6608
swri-robotics/ConnTact
src/conntact/assembly_algorithm_blocks.py
[ "Apache-2.0" ]
Python
run_loop
null
def run_loop(self): """Runs the method with name matching the state name. Superceded by AssemblyStep class type if one exists. """ state_name=str(self.state) if("state_") in state_name: if(state_name in self.steps): #This step has been realized as a Step class...
Runs the method with name matching the state name. Superceded by AssemblyStep class type if one exists.
Runs the method with name matching the state name. Superceded by AssemblyStep class type if one exists.
[ "Runs", "the", "method", "with", "name", "matching", "the", "state", "name", ".", "Superceded", "by", "AssemblyStep", "class", "type", "if", "one", "exists", "." ]
def run_loop(self): state_name=str(self.state) if("state_") in state_name: if(state_name in self.steps): if(not self.step): self.step = self.steps[state_name][0](self, *self.steps[state_name][1]) rospy.loginfo( Fore.GREEN + "Created ste...
[ "def", "run_loop", "(", "self", ")", ":", "state_name", "=", "str", "(", "self", ".", "state", ")", "if", "(", "\"state_\"", ")", "in", "state_name", ":", "if", "(", "state_name", "in", "self", ".", "steps", ")", ":", "if", "(", "not", "self", ".",...
Runs the method with name matching the state name.
[ "Runs", "the", "method", "with", "name", "matching", "the", "state", "name", "." ]
[ "\"\"\"Runs the method with name matching the state name. Superceded by AssemblyStep class type if one exists.\n \"\"\"", "#This step has been realized as a Step class", "#Set step to an instance of the referred class and pass in the parameters.", "# This step has been realized as a looping method." ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5214b68870ece3123bc4f5d2a4c1da7549fb6608
swri-robotics/ConnTact
src/conntact/assembly_algorithm_blocks.py
[ "Apache-2.0" ]
Python
algorithm_execute
null
def algorithm_execute(self): """Main execution loop. A True exit state will cause the buffered Trigger "self.next_trigger" to be run, changing the state. If using a state realized as an AssemblyStep class, we delete the old step here. Also executes the once-per-cycle non-step commands needed for continuous safe...
Main execution loop. A True exit state will cause the buffered Trigger "self.next_trigger" to be run, changing the state. If using a state realized as an AssemblyStep class, we delete the old step here. Also executes the once-per-cycle non-step commands needed for continuous safe operation.
Main execution loop. A True exit state will cause the buffered Trigger "self.next_trigger" to be run, changing the state. If using a state realized as an AssemblyStep class, we delete the old step here. Also executes the once-per-cycle non-step commands needed for continuous safe operation.
[ "Main", "execution", "loop", ".", "A", "True", "exit", "state", "will", "cause", "the", "buffered", "Trigger", "\"", "self", ".", "next_trigger", "\"", "to", "be", "run", "changing", "the", "state", ".", "If", "using", "a", "state", "realized", "as", "an...
def algorithm_execute(self): self.completion_confidence = 0 self.next_trigger, self.switch_state = self.post_action(CHECK_FEEDBACK_TRIGGER) rospy.loginfo(Fore.BLACK + Back.GREEN + "Beginning search algorithm. "+Style.RESET_ALL) while not rospy.is_shutdown() and self.state != EXIT_STATE: ...
[ "def", "algorithm_execute", "(", "self", ")", ":", "self", ".", "completion_confidence", "=", "0", "self", ".", "next_trigger", ",", "self", ".", "switch_state", "=", "self", ".", "post_action", "(", "CHECK_FEEDBACK_TRIGGER", ")", "rospy", ".", "loginfo", "(",...
Main execution loop.
[ "Main", "execution", "loop", "." ]
[ "\"\"\"Main execution loop. A True exit state will cause the buffered Trigger \"self.next_trigger\" to be run, changing the state. If using a state realized as an AssemblyStep class, we delete the old step here. Also executes the once-per-cycle non-step commands needed for continuous safe operation.\n \"\"\"...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5214b68870ece3123bc4f5d2a4c1da7549fb6608
swri-robotics/ConnTact
src/conntact/assembly_algorithm_blocks.py
[ "Apache-2.0" ]
Python
arbitrary_axis_comply
<not_specific>
def arbitrary_axis_comply(self, direction_vector = [0,0,1], desired_orientation = [0, 1, 0, 0]): """Generates a command pose vector which causes the robot to hold a certain orientation and comply in one dimension while staying on track in the others. :param desiredTaskSpacePosition: (array-like...
Generates a command pose vector which causes the robot to hold a certain orientation and comply in one dimension while staying on track in the others. :param desiredTaskSpacePosition: (array-like) vector indicating hole position in robot frame :param direction_vector: (array-like list of bools)...
Generates a command pose vector which causes the robot to hold a certain orientation and comply in one dimension while staying on track in the others.
[ "Generates", "a", "command", "pose", "vector", "which", "causes", "the", "robot", "to", "hold", "a", "certain", "orientation", "and", "comply", "in", "one", "dimension", "while", "staying", "on", "track", "in", "the", "others", "." ]
def arbitrary_axis_comply(self, direction_vector = [0,0,1], desired_orientation = [0, 1, 0, 0]): pose_position = self.current_pose.transform.translation if(not direction_vector[0]): pose_position.x = self.target_hole_pose.pose.position.x if(not direction_vector[1]): pose_...
[ "def", "arbitrary_axis_comply", "(", "self", ",", "direction_vector", "=", "[", "0", ",", "0", ",", "1", "]", ",", "desired_orientation", "=", "[", "0", ",", "1", ",", "0", ",", "0", "]", ")", ":", "pose_position", "=", "self", ".", "current_pose", "...
Generates a command pose vector which causes the robot to hold a certain orientation and comply in one dimension while staying on track in the others.
[ "Generates", "a", "command", "pose", "vector", "which", "causes", "the", "robot", "to", "hold", "a", "certain", "orientation", "and", "comply", "in", "one", "dimension", "while", "staying", "on", "track", "in", "the", "others", "." ]
[ "\"\"\"Generates a command pose vector which causes the robot to hold a certain orientation\n and comply in one dimension while staying on track in the others.\n :param desiredTaskSpacePosition: (array-like) vector indicating hole position in robot frame\n :param direction_vector: (array-like ...
[ { "param": "self", "type": null }, { "param": "direction_vector", "type": null }, { "param": "desired_orientation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "direction_vector", "type": null, "docstring": "(array-like list of ...
5214b68870ece3123bc4f5d2a4c1da7549fb6608
swri-robotics/ConnTact
src/conntact/assembly_algorithm_blocks.py
[ "Apache-2.0" ]
Python
updateCommands
null
def updateCommands(self): '''Updates the commanded position and wrench. These are published in the AlgorithmBlocks main loop. ''' #Command wrench self.assembly.wrench_vec = self.assembly.get_command_wrench(self.seeking_force) #Command pose self.assembly.pose_vec = self.a...
Updates the commanded position and wrench. These are published in the AlgorithmBlocks main loop.
Updates the commanded position and wrench. These are published in the AlgorithmBlocks main loop.
[ "Updates", "the", "commanded", "position", "and", "wrench", ".", "These", "are", "published", "in", "the", "AlgorithmBlocks", "main", "loop", "." ]
def updateCommands(self): self.assembly.wrench_vec = self.assembly.get_command_wrench(self.seeking_force) self.assembly.pose_vec = self.assembly.arbitrary_axis_comply(self.comply_axes)
[ "def", "updateCommands", "(", "self", ")", ":", "self", ".", "assembly", ".", "wrench_vec", "=", "self", ".", "assembly", ".", "get_command_wrench", "(", "self", ".", "seeking_force", ")", "self", ".", "assembly", ".", "pose_vec", "=", "self", ".", "assemb...
Updates the commanded position and wrench.
[ "Updates", "the", "commanded", "position", "and", "wrench", "." ]
[ "'''Updates the commanded position and wrench. These are published in the AlgorithmBlocks main loop.\n '''", "#Command wrench", "#Command pose" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5214b68870ece3123bc4f5d2a4c1da7549fb6608
swri-robotics/ConnTact
src/conntact/assembly_algorithm_blocks.py
[ "Apache-2.0" ]
Python
checkCompletion
<not_specific>
def checkCompletion(self): """Check if the step is complete. Default behavior is to check the exit conditions and gain/lose confidence between 0 and 1. ExitConditions returning True adds a step toward 1; False steps down toward 0. Once confidence is above exitThreshold, a timer begins for duration exitPeriod. ...
Check if the step is complete. Default behavior is to check the exit conditions and gain/lose confidence between 0 and 1. ExitConditions returning True adds a step toward 1; False steps down toward 0. Once confidence is above exitThreshold, a timer begins for duration exitPeriod.
Check if the step is complete. Default behavior is to check the exit conditions and gain/lose confidence between 0 and 1. ExitConditions returning True adds a step toward 1; False steps down toward 0. Once confidence is above exitThreshold, a timer begins for duration exitPeriod.
[ "Check", "if", "the", "step", "is", "complete", ".", "Default", "behavior", "is", "to", "check", "the", "exit", "conditions", "and", "gain", "/", "lose", "confidence", "between", "0", "and", "1", ".", "ExitConditions", "returning", "True", "adds", "a", "st...
def checkCompletion(self): if(self.exitConditions()): if(self.completion_confidence < 1): self.completion_confidence += 1/(self.assembly._rate_selected) if(self.completion_confidence > self.exitThreshold): if(self.holdStartTime == 0): s...
[ "def", "checkCompletion", "(", "self", ")", ":", "if", "(", "self", ".", "exitConditions", "(", ")", ")", ":", "if", "(", "self", ".", "completion_confidence", "<", "1", ")", ":", "self", ".", "completion_confidence", "+=", "1", "/", "(", "self", ".", ...
Check if the step is complete.
[ "Check", "if", "the", "step", "is", "complete", "." ]
[ "\"\"\"Check if the step is complete. Default behavior is to check the exit conditions and gain/lose confidence between 0 and 1. ExitConditions returning True adds a step toward 1; False steps down toward 0. Once confidence is above exitThreshold, a timer begins for duration exitPeriod.\n \"\"\"", "#Start ...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5214b68870ece3123bc4f5d2a4c1da7549fb6608
swri-robotics/ConnTact
src/conntact/assembly_algorithm_blocks.py
[ "Apache-2.0" ]
Python
noForce
bool
def noForce(self)->bool: '''Checks the current forces against an expected force of zero, helpfully telling us if the robot is in free motion :return: (bool) whether the force is fairly close to zero. ''' return self.assembly.checkIfColliding(np.zeros(3))
Checks the current forces against an expected force of zero, helpfully telling us if the robot is in free motion :return: (bool) whether the force is fairly close to zero.
Checks the current forces against an expected force of zero, helpfully telling us if the robot is in free motion
[ "Checks", "the", "current", "forces", "against", "an", "expected", "force", "of", "zero", "helpfully", "telling", "us", "if", "the", "robot", "is", "in", "free", "motion" ]
def noForce(self)->bool: return self.assembly.checkIfColliding(np.zeros(3))
[ "def", "noForce", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "assembly", ".", "checkIfColliding", "(", "np", ".", "zeros", "(", "3", ")", ")" ]
Checks the current forces against an expected force of zero, helpfully telling us if the robot is in free motion
[ "Checks", "the", "current", "forces", "against", "an", "expected", "force", "of", "zero", "helpfully", "telling", "us", "if", "the", "robot", "is", "in", "free", "motion" ]
[ "'''Checks the current forces against an expected force of zero, helpfully telling us if the robot is in free motion\n :return: (bool) whether the force is fairly close to zero.\n '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "(bool) whether the force is fairly close to zero.", "docstring_tokens": [ "(", "bool", ")", "whether", "the", "force", "is", "fairly", "close", "to", "zero", "." ], ...
764cb4af70aebc6822710b556aa2b7c7ef847790
microsoft/times-excel-reader
times_excel_reader.py
[ "MIT" ]
Python
merge_tables
Dict[str, DataFrame]
def merge_tables(tables: List[EmbeddedXlTable]) -> Dict[str, DataFrame]: """Merge tables of the same types""" result = {} for key, value in groupby(sorted(tables, key=lambda t: t.tag), lambda t: t.tag): group = list(value) if not all(set(t.dataframe.columns) == set(group[0].dataframe.columns...
Merge tables of the same types
Merge tables of the same types
[ "Merge", "tables", "of", "the", "same", "types" ]
def merge_tables(tables: List[EmbeddedXlTable]) -> Dict[str, DataFrame]: result = {} for key, value in groupby(sorted(tables, key=lambda t: t.tag), lambda t: t.tag): group = list(value) if not all(set(t.dataframe.columns) == set(group[0].dataframe.columns) for t in group): cols = [("...
[ "def", "merge_tables", "(", "tables", ":", "List", "[", "EmbeddedXlTable", "]", ")", "->", "Dict", "[", "str", ",", "DataFrame", "]", ":", "result", "=", "{", "}", "for", "key", ",", "value", "in", "groupby", "(", "sorted", "(", "tables", ",", "key",...
Merge tables of the same types
[ "Merge", "tables", "of", "the", "same", "types" ]
[ "\"\"\"Merge tables of the same types\"\"\"" ]
[ { "param": "tables", "type": "List[EmbeddedXlTable]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tables", "type": "List[EmbeddedXlTable]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
764cb4af70aebc6822710b556aa2b7c7ef847790
microsoft/times-excel-reader
times_excel_reader.py
[ "MIT" ]
Python
expand_rows
EmbeddedXlTable
def expand_rows(table: EmbeddedXlTable) -> EmbeddedXlTable: """Expand out certain columns with entries containing commas""" def has_comma(s): return isinstance(s,str) and ',' in s def split_by_commas(s): if has_comma(s): return s.split(',') else: return s ...
Expand out certain columns with entries containing commas
Expand out certain columns with entries containing commas
[ "Expand", "out", "certain", "columns", "with", "entries", "containing", "commas" ]
def expand_rows(table: EmbeddedXlTable) -> EmbeddedXlTable: def has_comma(s): return isinstance(s,str) and ',' in s def split_by_commas(s): if has_comma(s): return s.split(',') else: return s df = table.dataframe.copy() c = df.applymap(has_comma) colum...
[ "def", "expand_rows", "(", "table", ":", "EmbeddedXlTable", ")", "->", "EmbeddedXlTable", ":", "def", "has_comma", "(", "s", ")", ":", "return", "isinstance", "(", "s", ",", "str", ")", "and", "','", "in", "s", "def", "split_by_commas", "(", "s", ")", ...
Expand out certain columns with entries containing commas
[ "Expand", "out", "certain", "columns", "with", "entries", "containing", "commas" ]
[ "\"\"\"Expand out certain columns with entries containing commas\"\"\"", "# Transform comma-separated strings into lists", "# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html#pandas.DataFrame.explode" ]
[ { "param": "table", "type": "EmbeddedXlTable" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "table", "type": "EmbeddedXlTable", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c1ebe5730bc8de2586cbb09405a1f3a2ebbd899
Brian-Williams/coronavirus
parser.py
[ "Apache-2.0" ]
Python
prep_es
null
def prep_es(es): """Cleanup existing indices and apply mapping""" if es.indices.exists(INDEX) is True: es.indices.delete(index=INDEX, ignore=[400, 404]) mapping = Path("mapping.json") with mapping.open() as m: es.indices.create(INDEX, body=json.load(m))
Cleanup existing indices and apply mapping
Cleanup existing indices and apply mapping
[ "Cleanup", "existing", "indices", "and", "apply", "mapping" ]
def prep_es(es): if es.indices.exists(INDEX) is True: es.indices.delete(index=INDEX, ignore=[400, 404]) mapping = Path("mapping.json") with mapping.open() as m: es.indices.create(INDEX, body=json.load(m))
[ "def", "prep_es", "(", "es", ")", ":", "if", "es", ".", "indices", ".", "exists", "(", "INDEX", ")", "is", "True", ":", "es", ".", "indices", ".", "delete", "(", "index", "=", "INDEX", ",", "ignore", "=", "[", "400", ",", "404", "]", ")", "mapp...
Cleanup existing indices and apply mapping
[ "Cleanup", "existing", "indices", "and", "apply", "mapping" ]
[ "\"\"\"Cleanup existing indices and apply mapping\"\"\"" ]
[ { "param": "es", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "es", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c1ebe5730bc8de2586cbb09405a1f3a2ebbd899
Brian-Williams/coronavirus
parser.py
[ "Apache-2.0" ]
Python
data_getter
null
def data_getter(dir_url): """Iterator for corvid data, returns (<csv_data>, <year month day: str>""" # not saving files for now # Path(DATA_DIR).mkdir(exist_ok=True) # for x in Path(DATA_DIR).iterdir(): # x.unlink() r = requests.get(dir_url) r.raise_for_status() files = r.json() ...
Iterator for corvid data, returns (<csv_data>, <year month day: str>
Iterator for corvid data, returns (,
[ "Iterator", "for", "corvid", "data", "returns", "(" ]
def data_getter(dir_url): r = requests.get(dir_url) r.raise_for_status() files = r.json() for file in files: if file.get('type') != "file": continue if file.get('name') in [".gitignore", "README.md"]: continue dl_url = file.get('download_url') if d...
[ "def", "data_getter", "(", "dir_url", ")", ":", "r", "=", "requests", ".", "get", "(", "dir_url", ")", "r", ".", "raise_for_status", "(", ")", "files", "=", "r", ".", "json", "(", ")", "for", "file", "in", "files", ":", "if", "file", ".", "get", ...
Iterator for corvid data, returns (<csv_data>, <year month day: str>
[ "Iterator", "for", "corvid", "data", "returns", "(", "<csv_data", ">", "<year", "month", "day", ":", "str", ">" ]
[ "\"\"\"Iterator for corvid data, returns (<csv_data>, <year month day: str>\"\"\"", "# not saving files for now", "# Path(DATA_DIR).mkdir(exist_ok=True)", "# for x in Path(DATA_DIR).iterdir():", "# x.unlink()", "# name example: 02-04-2020.csv", "# TODO: consider dropping date yield and trusting \"La...
[ { "param": "dir_url", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dir_url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e689c295635b386c127135ebaea7d0ad0389fc12
sumnerevans/advent-of-code
2020/19.py
[ "MIT" ]
Python
part1
int
def part1() -> int: """ This is the grossest way to solve this, but I think it's one of the best ways because of the nice properties of the input. Basically, I'm constructing a regular expression from the grammar (which luckily already is regular for Part 1). I originally tried to do this inte...
This is the grossest way to solve this, but I think it's one of the best ways because of the nice properties of the input. Basically, I'm constructing a regular expression from the grammar (which luckily already is regular for Part 1). I originally tried to do this intelligently with another recu...
This is the grossest way to solve this, but I think it's one of the best ways because of the nice properties of the input. Basically, I'm constructing a regular expression from the grammar (which luckily already is regular for Part 1). I originally tried to do this intelligently with another recursive descent parser,...
[ "This", "is", "the", "grossest", "way", "to", "solve", "this", "but", "I", "think", "it", "'", "s", "one", "of", "the", "best", "ways", "because", "of", "the", "nice", "properties", "of", "the", "input", ".", "Basically", "I", "'", "m", "constructing",...
def part1() -> int: ans = 0 def convert(rn) -> str: parts = [] for r in RULES[rn]: if isinstance(r, str): return r else: parts.append("".join(convert(x) for x in r)) return "(" + "|".join(parts) + ")" regex = convert(0) for ...
[ "def", "part1", "(", ")", "->", "int", ":", "ans", "=", "0", "def", "convert", "(", "rn", ")", "->", "str", ":", "\"\"\"\n This function converts a rule number to a regex. It uses the ``for`` loop to\n deal with the OR cases, and then joins them with \"|\"s. For eac...
This is the grossest way to solve this, but I think it's one of the best ways because of the nice properties of the input.
[ "This", "is", "the", "grossest", "way", "to", "solve", "this", "but", "I", "think", "it", "'", "s", "one", "of", "the", "best", "ways", "because", "of", "the", "nice", "properties", "of", "the", "input", "." ]
[ "\"\"\"\n This is the grossest way to solve this, but I think it's one of the best ways\n because of the nice properties of the input.\n\n Basically, I'm constructing a regular expression from the grammar (which luckily\n already is regular for Part 1).\n\n I originally tried to do this intelligently...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
e689c295635b386c127135ebaea7d0ad0389fc12
sumnerevans/advent-of-code
2020/19.py
[ "MIT" ]
Python
convert
str
def convert(rn) -> str: """ This function converts a rule number to a regex. It uses the ``for`` loop to deal with the OR cases, and then joins them with "|"s. For each of the sequence rules, it calls itself recursively to generate a regex for the sub-rule. """ parts = []...
This function converts a rule number to a regex. It uses the ``for`` loop to deal with the OR cases, and then joins them with "|"s. For each of the sequence rules, it calls itself recursively to generate a regex for the sub-rule.
This function converts a rule number to a regex. It uses the ``for`` loop to deal with the OR cases, and then joins them with "|"s. For each of the sequence rules, it calls itself recursively to generate a regex for the sub-rule.
[ "This", "function", "converts", "a", "rule", "number", "to", "a", "regex", ".", "It", "uses", "the", "`", "`", "for", "`", "`", "loop", "to", "deal", "with", "the", "OR", "cases", "and", "then", "joins", "them", "with", "\"", "|", "\"", "s", ".", ...
def convert(rn) -> str: parts = [] for r in RULES[rn]: if isinstance(r, str): return r else: parts.append("".join(convert(x) for x in r)) return "(" + "|".join(parts) + ")"
[ "def", "convert", "(", "rn", ")", "->", "str", ":", "parts", "=", "[", "]", "for", "r", "in", "RULES", "[", "rn", "]", ":", "if", "isinstance", "(", "r", ",", "str", ")", ":", "return", "r", "else", ":", "parts", ".", "append", "(", "\"\"", "...
This function converts a rule number to a regex.
[ "This", "function", "converts", "a", "rule", "number", "to", "a", "regex", "." ]
[ "\"\"\"\n This function converts a rule number to a regex. It uses the ``for`` loop to\n deal with the OR cases, and then joins them with \"|\"s. For each of the sequence\n rules, it calls itself recursively to generate a regex for the sub-rule.\n \"\"\"" ]
[ { "param": "rn", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "rn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e689c295635b386c127135ebaea7d0ad0389fc12
sumnerevans/advent-of-code
2020/19.py
[ "MIT" ]
Python
convert
str
def convert(rn, n11s) -> str: """ This function converts a rule number to a regex. It uses the ``for`` loop to deal with the OR cases, and then joins them with "|"s. For each of the sequence rules, it calls itself recursively to generate a regex for the sub-rule. """ part...
This function converts a rule number to a regex. It uses the ``for`` loop to deal with the OR cases, and then joins them with "|"s. For each of the sequence rules, it calls itself recursively to generate a regex for the sub-rule.
This function converts a rule number to a regex. It uses the ``for`` loop to deal with the OR cases, and then joins them with "|"s. For each of the sequence rules, it calls itself recursively to generate a regex for the sub-rule.
[ "This", "function", "converts", "a", "rule", "number", "to", "a", "regex", ".", "It", "uses", "the", "`", "`", "for", "`", "`", "loop", "to", "deal", "with", "the", "OR", "cases", "and", "then", "joins", "them", "with", "\"", "|", "\"", "s", ".", ...
def convert(rn, n11s) -> str: parts = [] if rn == 8: return "(" + convert(42, n11s) + ")" + "+" elif rn == 11: if n11s == 0: return "(" + convert(42, n11s) + convert(31, n11s) + ")" return ( "((" + convert(42, n1...
[ "def", "convert", "(", "rn", ",", "n11s", ")", "->", "str", ":", "parts", "=", "[", "]", "if", "rn", "==", "8", ":", "return", "\"(\"", "+", "convert", "(", "42", ",", "n11s", ")", "+", "\")\"", "+", "\"+\"", "elif", "rn", "==", "11", ":", "i...
This function converts a rule number to a regex.
[ "This", "function", "converts", "a", "rule", "number", "to", "a", "regex", "." ]
[ "\"\"\"\n This function converts a rule number to a regex. It uses the ``for`` loop to\n deal with the OR cases, and then joins them with \"|\"s. For each of the sequence\n rules, it calls itself recursively to generate a regex for the sub-rule.\n \"\"\"" ]
[ { "param": "rn", "type": null }, { "param": "n11s", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "rn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n11s", "type": null, "docstring": null, "docstring_tokens": [],...
286348ef59618c938b496e91e98ee88c10df3727
sumnerevans/advent-of-code
2020/06.py
[ "MIT" ]
Python
part1
<not_specific>
def part1(): """ This part is just a sum of the number of letters in the *union* of all of the responses for each group. """ return sum(len(set.union(*g)) for g in groups)
This part is just a sum of the number of letters in the *union* of all of the responses for each group.
This part is just a sum of the number of letters in the *union* of all of the responses for each group.
[ "This", "part", "is", "just", "a", "sum", "of", "the", "number", "of", "letters", "in", "the", "*", "union", "*", "of", "all", "of", "the", "responses", "for", "each", "group", "." ]
def part1(): return sum(len(set.union(*g)) for g in groups)
[ "def", "part1", "(", ")", ":", "return", "sum", "(", "len", "(", "set", ".", "union", "(", "*", "g", ")", ")", "for", "g", "in", "groups", ")" ]
This part is just a sum of the number of letters in the *union* of all of the responses for each group.
[ "This", "part", "is", "just", "a", "sum", "of", "the", "number", "of", "letters", "in", "the", "*", "union", "*", "of", "all", "of", "the", "responses", "for", "each", "group", "." ]
[ "\"\"\"\n This part is just a sum of the number of letters in the *union* of all of the\n responses for each group.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
286348ef59618c938b496e91e98ee88c10df3727
sumnerevans/advent-of-code
2020/06.py
[ "MIT" ]
Python
part2
<not_specific>
def part2(): """ This part is just a sum of the number of letters in the *intersection* of all of the responses for each group. """ return sum(len(set.intersection(*g)) for g in groups) # The following was what I implemented when I solved night-of. The nice thing about # this method is that...
This part is just a sum of the number of letters in the *intersection* of all of the responses for each group.
This part is just a sum of the number of letters in the *intersection* of all of the responses for each group.
[ "This", "part", "is", "just", "a", "sum", "of", "the", "number", "of", "letters", "in", "the", "*", "intersection", "*", "of", "all", "of", "the", "responses", "for", "each", "group", "." ]
def part2(): return sum(len(set.intersection(*g)) for g in groups) s = 0 for g in groups: for c in "abcdefghijklmnopqrstuvwxyz": no = False for p in g: if c not in p: no = True break if not no: ...
[ "def", "part2", "(", ")", ":", "return", "sum", "(", "len", "(", "set", ".", "intersection", "(", "*", "g", ")", ")", "for", "g", "in", "groups", ")", "s", "=", "0", "for", "g", "in", "groups", ":", "for", "c", "in", "\"abcdefghijklmnopqrstuvwxyz\"...
This part is just a sum of the number of letters in the *intersection* of all of the responses for each group.
[ "This", "part", "is", "just", "a", "sum", "of", "the", "number", "of", "letters", "in", "the", "*", "intersection", "*", "of", "all", "of", "the", "responses", "for", "each", "group", "." ]
[ "\"\"\"\n This part is just a sum of the number of letters in the *intersection* of all of the\n responses for each group.\n \"\"\"", "# The following was what I implemented when I solved night-of. The nice thing about", "# this method is that it was very easy to think about and I didn't take too much"...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0774c356585e1d03b22bdc1425adb20289038353
sumnerevans/advent-of-code
2021/18.py
[ "MIT" ]
Python
reduce_split
<not_specific>
def reduce_split(pair): """ To split a regular number, replace it with a pair; the left element of the pair should be the regular number divided by two and rounded down, while the right element of the pair should be the regular number divided by two and rounded up. For example, 10 becomes [5,5], 11 ...
To split a regular number, replace it with a pair; the left element of the pair should be the regular number divided by two and rounded down, while the right element of the pair should be the regular number divided by two and rounded up. For example, 10 becomes [5,5], 11 becomes [5,6], 12 becomes [...
To split a regular number, replace it with a pair; the left element of the pair should be the regular number divided by two and rounded down, while the right element of the pair should be the regular number divided by two and rounded up.
[ "To", "split", "a", "regular", "number", "replace", "it", "with", "a", "pair", ";", "the", "left", "element", "of", "the", "pair", "should", "be", "the", "regular", "number", "divided", "by", "two", "and", "rounded", "down", "while", "the", "right", "ele...
def reduce_split(pair): if isinstance(pair, int): if pair >= 10: return [math.floor(pair / 2), math.ceil(pair / 2)] return pair split_l = reduce_split(pair[0]) if split_l != pair[0]: return [split_l, pair[1]] else: return [split_l, reduce_split(pair[1])]
[ "def", "reduce_split", "(", "pair", ")", ":", "if", "isinstance", "(", "pair", ",", "int", ")", ":", "if", "pair", ">=", "10", ":", "return", "[", "math", ".", "floor", "(", "pair", "/", "2", ")", ",", "math", ".", "ceil", "(", "pair", "/", "2"...
To split a regular number, replace it with a pair; the left element of the pair should be the regular number divided by two and rounded down, while the right element of the pair should be the regular number divided by two and rounded up.
[ "To", "split", "a", "regular", "number", "replace", "it", "with", "a", "pair", ";", "the", "left", "element", "of", "the", "pair", "should", "be", "the", "regular", "number", "divided", "by", "two", "and", "rounded", "down", "while", "the", "right", "ele...
[ "\"\"\"\n To split a regular number, replace it with a pair; the left element of the\n pair should be the regular number divided by two and rounded down, while the\n right element of the pair should be the regular number divided by two and\n rounded up. For example, 10 becomes [5,5], 11 becomes [5,6], 1...
[ { "param": "pair", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pair", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6bc89a4f900976f8f989de203dc12541f18819cf
sumnerevans/advent-of-code
2018/07.py
[ "MIT" ]
Python
part1
str
def part1() -> str: """ I'm solving Part 1 using a BFS-like algorithm. I maintain a *frontier*, effectively the set of elements that can be performed next. The rules state if there are multiple jobs that can be perfomred at once, the one that is lexicographicaly first should be performed. To accompl...
I'm solving Part 1 using a BFS-like algorithm. I maintain a *frontier*, effectively the set of elements that can be performed next. The rules state if there are multiple jobs that can be perfomred at once, the one that is lexicographicaly first should be performed. To accomplish this, I'm storing the f...
I'm solving Part 1 using a BFS-like algorithm. I maintain a *frontier*, effectively the set of elements that can be performed next. The rules state if there are multiple jobs that can be perfomred at once, the one that is lexicographicaly first should be performed. To accomplish this, I'm storing the frontier in a heap...
[ "I", "'", "m", "solving", "Part", "1", "using", "a", "BFS", "-", "like", "algorithm", ".", "I", "maintain", "a", "*", "frontier", "*", "effectively", "the", "set", "of", "elements", "that", "can", "be", "performed", "next", ".", "The", "rules", "state"...
def part1() -> str: frontier = deepcopy(STARTS) heapq.heapify(frontier) satisfied = set() s = "" while frontier: current = heapq.heappop(frontier) if current in satisfied: continue sat = True for dep in STEP_DEPENDENCIES[current]: if dep not in...
[ "def", "part1", "(", ")", "->", "str", ":", "frontier", "=", "deepcopy", "(", "STARTS", ")", "heapq", ".", "heapify", "(", "frontier", ")", "satisfied", "=", "set", "(", ")", "s", "=", "\"\"", "while", "frontier", ":", "current", "=", "heapq", ".", ...
I'm solving Part 1 using a BFS-like algorithm.
[ "I", "'", "m", "solving", "Part", "1", "using", "a", "BFS", "-", "like", "algorithm", "." ]
[ "\"\"\"\n I'm solving Part 1 using a BFS-like algorithm. I maintain a *frontier*, effectively\n the set of elements that can be performed next. The rules state if there are\n multiple jobs that can be perfomred at once, the one that is lexicographicaly first\n should be performed. To accomplish this, I'...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
6bc89a4f900976f8f989de203dc12541f18819cf
sumnerevans/advent-of-code
2018/07.py
[ "MIT" ]
Python
part2
int
def part2() -> int: """ I'm doing Part 2 using a discrete event simulation (DES). I'm assuming there's a way to do this using a topological sort as well, but I wanted to implement a DES. The basic idea of a DES is that you keep a priority queue of "events". Each event is a *discrete event* and muta...
I'm doing Part 2 using a discrete event simulation (DES). I'm assuming there's a way to do this using a topological sort as well, but I wanted to implement a DES. The basic idea of a DES is that you keep a priority queue of "events". Each event is a *discrete event* and mutates the state of the world ...
I'm doing Part 2 using a discrete event simulation (DES). I'm assuming there's a way to do this using a topological sort as well, but I wanted to implement a DES. The basic idea of a DES is that you keep a priority queue of "events". Each event is a *discrete event* and mutates the state of the world in some way. In m...
[ "I", "'", "m", "doing", "Part", "2", "using", "a", "discrete", "event", "simulation", "(", "DES", ")", ".", "I", "'", "m", "assuming", "there", "'", "s", "a", "way", "to", "do", "this", "using", "a", "topological", "sort", "as", "well", "but", "I",...
def part2() -> int: BASE_TIME = 60 if not test else 0 WORKERS = 6 if not test else 2 job_to_time = {c: BASE_TIME + ord(c) - ord("A") + 1 for c in string.ascii_uppercase} T = 0 unstarted: Set[str] = set(ans_part1) satisfied: Set[str] = set() workers_available: int = 0 started: Set[str] = ...
[ "def", "part2", "(", ")", "->", "int", ":", "BASE_TIME", "=", "60", "if", "not", "test", "else", "0", "WORKERS", "=", "6", "if", "not", "test", "else", "2", "job_to_time", "=", "{", "c", ":", "BASE_TIME", "+", "ord", "(", "c", ")", "-", "ord", ...
I'm doing Part 2 using a discrete event simulation (DES).
[ "I", "'", "m", "doing", "Part", "2", "using", "a", "discrete", "event", "simulation", "(", "DES", ")", "." ]
[ "\"\"\"\n I'm doing Part 2 using a discrete event simulation (DES). I'm assuming there's a way\n to do this using a topological sort as well, but I wanted to implement a DES.\n\n The basic idea of a DES is that you keep a priority queue of \"events\". Each event is\n a *discrete event* and mutates the s...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fc4679f9c6aadc9df79bac5e7a717e15e2ab2d9d
sumnerevans/advent-of-code
2020/16.py
[ "MIT" ]
Python
infer_one_to_one_from_possibles
Dict[K, V]
def infer_one_to_one_from_possibles(possibles: Dict[K, Set[V]]) -> Dict[K, V]: """ This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value. For example:: A -> {X, Y} ...
This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value. For example:: A -> {X, Y} B -> {Y} C -> {X, Z} then ``B`` must be ``Y``, which means that ``A`` c...
This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value. For example:.
[ "This", "goes", "through", "a", "dictionary", "of", "key", "to", "potential", "values", "and", "computes", "the", "true", "value", "using", "simple", "inference", "where", "if", "a", "key", "can", "only", "be", "a", "single", "value", "then", "it", "must",...
def infer_one_to_one_from_possibles(possibles: Dict[K, Set[V]]) -> Dict[K, V]: inferred = {} while len(possibles): for key, possible_fields in possibles.items(): if len(possible_fields) == 1: inferred[key] = possible_fields.pop() remove_item = inferred[key] ...
[ "def", "infer_one_to_one_from_possibles", "(", "possibles", ":", "Dict", "[", "K", ",", "Set", "[", "V", "]", "]", ")", "->", "Dict", "[", "K", ",", "V", "]", ":", "inferred", "=", "{", "}", "while", "len", "(", "possibles", ")", ":", "for", "key",...
This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value.
[ "This", "goes", "through", "a", "dictionary", "of", "key", "to", "potential", "values", "and", "computes", "the", "true", "value", "using", "simple", "inference", "where", "if", "a", "key", "can", "only", "be", "a", "single", "value", "then", "it", "must",...
[ "\"\"\"\n This goes through a dictionary of key to potential values and computes the true\n value using simple inference where if a key can only be a single value, then it must\n be that value. For example::\n\n A -> {X, Y}\n B -> {Y}\n C -> {X, Z}\n\n then ``B`` must be ``Y``, whic...
[ { "param": "possibles", "type": "Dict[K, Set[V]]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "possibles", "type": "Dict[K, Set[V]]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c6368be1284f6d97c63b027c4d16577419a8883c
sumnerevans/advent-of-code
2021/17.py
[ "MIT" ]
Python
allints
Iterator[int]
def allints(s: str) -> Iterator[int]: """ Returns a list of all of the integers in the string. """ return map(lambda m: int(m.group(0)), re.finditer(r"-?\d+", s))
Returns a list of all of the integers in the string.
Returns a list of all of the integers in the string.
[ "Returns", "a", "list", "of", "all", "of", "the", "integers", "in", "the", "string", "." ]
def allints(s: str) -> Iterator[int]: return map(lambda m: int(m.group(0)), re.finditer(r"-?\d+", s))
[ "def", "allints", "(", "s", ":", "str", ")", "->", "Iterator", "[", "int", "]", ":", "return", "map", "(", "lambda", "m", ":", "int", "(", "m", ".", "group", "(", "0", ")", ")", ",", "re", ".", "finditer", "(", "r\"-?\\d+\"", ",", "s", ")", "...
Returns a list of all of the integers in the string.
[ "Returns", "a", "list", "of", "all", "of", "the", "integers", "in", "the", "string", "." ]
[ "\"\"\"\n Returns a list of all of the integers in the string.\n \"\"\"" ]
[ { "param": "s", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "s", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5096ab2e11f1b4732fd90599b66c7f755b97fc17
sumnerevans/advent-of-code
2021/23.py
[ "MIT" ]
Python
dirange
Generator[int, None, None]
def dirange(start, end=None, step=1) -> Generator[int, None, None]: """ Directional, inclusive range. This range function is an inclusive version of :class:`range` that figures out the correct step direction to make sure that it goes from `start` to `end`, even if `end` is before `start`. >>> diran...
Directional, inclusive range. This range function is an inclusive version of :class:`range` that figures out the correct step direction to make sure that it goes from `start` to `end`, even if `end` is before `start`. >>> dirange(2, -2) [2, 1, 0, -1, -2] >>> dirange(-2) [0, -1, -2] >>>...
Directional, inclusive range. This range function is an inclusive version of
[ "Directional", "inclusive", "range", ".", "This", "range", "function", "is", "an", "inclusive", "version", "of" ]
def dirange(start, end=None, step=1) -> Generator[int, None, None]: assert step > 0 if end is None: start, end = 0, start if end >= start: yield from irange(start, end, step) else: yield from range(start, end - 1, -step)
[ "def", "dirange", "(", "start", ",", "end", "=", "None", ",", "step", "=", "1", ")", "->", "Generator", "[", "int", ",", "None", ",", "None", "]", ":", "assert", "step", ">", "0", "if", "end", "is", "None", ":", "start", ",", "end", "=", "0", ...
Directional, inclusive range.
[ "Directional", "inclusive", "range", "." ]
[ "\"\"\"\n Directional, inclusive range. This range function is an inclusive version of\n :class:`range` that figures out the correct step direction to make sure that it goes\n from `start` to `end`, even if `end` is before `start`.\n\n >>> dirange(2, -2)\n [2, 1, 0, -1, -2]\n >>> dirange(-2)\n ...
[ { "param": "start", "type": null }, { "param": "end", "type": null }, { "param": "step", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "start", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "end", "type": null, "docstring": null, "docstring_tokens": [...
2d3a7a532a947ce67c92793ae91c4568b7458ae7
sumnerevans/advent-of-code
2017/02.py
[ "MIT" ]
Python
seqminmax
Tuple[int, int]
def seqminmax(sequence: Iterable[int]) -> Tuple[int, int]: """ Returns a tuple containing the minimum and maximum element of the ``sequence``. """ min_, max_ = math.inf, -math.inf for x in sequence: min_ = min(min_, x) max_ = max(max_, x) return int(min_), int(max_)
Returns a tuple containing the minimum and maximum element of the ``sequence``.
Returns a tuple containing the minimum and maximum element of the ``sequence``.
[ "Returns", "a", "tuple", "containing", "the", "minimum", "and", "maximum", "element", "of", "the", "`", "`", "sequence", "`", "`", "." ]
def seqminmax(sequence: Iterable[int]) -> Tuple[int, int]: min_, max_ = math.inf, -math.inf for x in sequence: min_ = min(min_, x) max_ = max(max_, x) return int(min_), int(max_)
[ "def", "seqminmax", "(", "sequence", ":", "Iterable", "[", "int", "]", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "min_", ",", "max_", "=", "math", ".", "inf", ",", "-", "math", ".", "inf", "for", "x", "in", "sequence", ":", "min_", ...
Returns a tuple containing the minimum and maximum element of the ``sequence``.
[ "Returns", "a", "tuple", "containing", "the", "minimum", "and", "maximum", "element", "of", "the", "`", "`", "sequence", "`", "`", "." ]
[ "\"\"\"\n Returns a tuple containing the minimum and maximum element of the ``sequence``.\n \"\"\"" ]
[ { "param": "sequence", "type": "Iterable[int]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sequence", "type": "Iterable[int]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b33bb324c04b3e52533f0d258edfadc323219e22
sumnerevans/advent-of-code
2018/08.py
[ "MIT" ]
Python
rot
Tuple[float, float]
def rot( x: float, y: float, deg: float, origin: Tuple[float, float] = (0, 0) ) -> Tuple[float, float]: """ Rotate a point by `deg` around the `origin`. This does floating-point math, so you may encounter precision errors. """ theta = deg * math.pi / 180 x2 = (x - origin[0]) * math.cos(theta...
Rotate a point by `deg` around the `origin`. This does floating-point math, so you may encounter precision errors.
Rotate a point by `deg` around the `origin`. This does floating-point math, so you may encounter precision errors.
[ "Rotate", "a", "point", "by", "`", "deg", "`", "around", "the", "`", "origin", "`", ".", "This", "does", "floating", "-", "point", "math", "so", "you", "may", "encounter", "precision", "errors", "." ]
def rot( x: float, y: float, deg: float, origin: Tuple[float, float] = (0, 0) ) -> Tuple[float, float]: theta = deg * math.pi / 180 x2 = (x - origin[0]) * math.cos(theta) - (y - origin[1]) * math.sin(theta) y2 = (x - origin[0]) * math.sin(theta) + (y - origin[1]) * math.cos(theta) return (x2 + origi...
[ "def", "rot", "(", "x", ":", "float", ",", "y", ":", "float", ",", "deg", ":", "float", ",", "origin", ":", "Tuple", "[", "float", ",", "float", "]", "=", "(", "0", ",", "0", ")", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "t...
Rotate a point by `deg` around the `origin`.
[ "Rotate", "a", "point", "by", "`", "deg", "`", "around", "the", "`", "origin", "`", "." ]
[ "\"\"\"\n Rotate a point by `deg` around the `origin`. This does floating-point math, so\n you may encounter precision errors.\n \"\"\"" ]
[ { "param": "x", "type": "float" }, { "param": "y", "type": "float" }, { "param": "deg", "type": "float" }, { "param": "origin", "type": "Tuple[float, float]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": "float", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "y", "type": "float", "docstring": null, "docstring_tokens": [...
b33bb324c04b3e52533f0d258edfadc323219e22
sumnerevans/advent-of-code
2018/08.py
[ "MIT" ]
Python
infer_one_to_one_from_possibles
<not_specific>
def infer_one_to_one_from_possibles(possibles: Dict[K, Set[V]]): """ This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value. For example: A -> {X, Y} B -> {Y} ...
This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value. For example: A -> {X, Y} B -> {Y} C -> {X, Z} then B -> Y, which means that A cannot be Y, thus A...
This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value. For example. then B -> Y, which means that A cannot be Y, thus A must be X, and by the same logic C must be Z.
[ "This", "goes", "through", "a", "dictionary", "of", "key", "to", "potential", "values", "and", "computes", "the", "true", "value", "using", "simple", "inference", "where", "if", "a", "key", "can", "only", "be", "a", "single", "value", "then", "it", "must",...
def infer_one_to_one_from_possibles(possibles: Dict[K, Set[V]]): inferred = {} while len(possibles): for idx, possible_fields in possibles.items(): if len(possible_fields) == 1: inferred[idx] = possible_fields.pop() remove_idx = idx break ...
[ "def", "infer_one_to_one_from_possibles", "(", "possibles", ":", "Dict", "[", "K", ",", "Set", "[", "V", "]", "]", ")", ":", "inferred", "=", "{", "}", "while", "len", "(", "possibles", ")", ":", "for", "idx", ",", "possible_fields", "in", "possibles", ...
This goes through a dictionary of key to potential values and computes the true value using simple inference where if a key can only be a single value, then it must be that value.
[ "This", "goes", "through", "a", "dictionary", "of", "key", "to", "potential", "values", "and", "computes", "the", "true", "value", "using", "simple", "inference", "where", "if", "a", "key", "can", "only", "be", "a", "single", "value", "then", "it", "must",...
[ "\"\"\"\n This goes through a dictionary of key to potential values and computes the true\n value using simple inference where if a key can only be a single value, then it must\n be that value. For example:\n\n A -> {X, Y}\n B -> {Y}\n C -> {X, Z}\n\n then B -> Y, which means that A...
[ { "param": "possibles", "type": "Dict[K, Set[V]]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "possibles", "type": "Dict[K, Set[V]]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b33bb324c04b3e52533f0d258edfadc323219e22
sumnerevans/advent-of-code
2018/08.py
[ "MIT" ]
Python
read_node
Tuple[Node, int]
def read_node(i, d=0) -> Tuple[Node, int]: """ Read in the node starting at index `i`. This is a recursive function that returns the node and the index that should be processed next (the one right after the last index we processed). """ N, M = seq[i], seq[i + 1] # number of children nodes and n...
Read in the node starting at index `i`. This is a recursive function that returns the node and the index that should be processed next (the one right after the last index we processed).
Read in the node starting at index `i`. This is a recursive function that returns the node and the index that should be processed next (the one right after the last index we processed).
[ "Read", "in", "the", "node", "starting", "at", "index", "`", "i", "`", ".", "This", "is", "a", "recursive", "function", "that", "returns", "the", "node", "and", "the", "index", "that", "should", "be", "processed", "next", "(", "the", "one", "right", "a...
def read_node(i, d=0) -> Tuple[Node, int]: N, M = seq[i], seq[i + 1] i += 2 children = [] for _ in range(N): node, i = read_node(i, d + 1) children.append(node) metadata = [] for _ in range(M): metadata.append(seq[i]) i += 1 return ((tuple(children), tuple(m...
[ "def", "read_node", "(", "i", ",", "d", "=", "0", ")", "->", "Tuple", "[", "Node", ",", "int", "]", ":", "N", ",", "M", "=", "seq", "[", "i", "]", ",", "seq", "[", "i", "+", "1", "]", "i", "+=", "2", "children", "=", "[", "]", "for", "_...
Read in the node starting at index `i`.
[ "Read", "in", "the", "node", "starting", "at", "index", "`", "i", "`", "." ]
[ "\"\"\"\n Read in the node starting at index `i`. This is a recursive function that returns\n the node and the index that should be processed next (the one right after the last\n index we processed).\n \"\"\"", "# number of children nodes and number of metadata items", "# Read in the children", "#...
[ { "param": "i", "type": null }, { "param": "d", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "i", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "d", "type": null, "docstring": null, "docstring_tokens": [], ...
b33bb324c04b3e52533f0d258edfadc323219e22
sumnerevans/advent-of-code
2018/08.py
[ "MIT" ]
Python
part1
int
def part1() -> int: """ Part 1 requires you to sum all of the metadata objects. I do this with the recursive traverse_sum function. """ def traverse_sum(node): """ Compute the sum of a given node by summing all of all of the metadata values and adding the sum of all of the r...
Part 1 requires you to sum all of the metadata objects. I do this with the recursive traverse_sum function.
Part 1 requires you to sum all of the metadata objects. I do this with the recursive traverse_sum function.
[ "Part", "1", "requires", "you", "to", "sum", "all", "of", "the", "metadata", "objects", ".", "I", "do", "this", "with", "the", "recursive", "traverse_sum", "function", "." ]
def part1() -> int: def traverse_sum(node): return sum(node[1]) + sum(map(traverse_sum, node[0])) return traverse_sum(TREE)
[ "def", "part1", "(", ")", "->", "int", ":", "def", "traverse_sum", "(", "node", ")", ":", "\"\"\"\n Compute the sum of a given node by summing all of all of the metadata values and\n adding the sum of all of the recursive calls to traverse_sum for all of the\n child no...
Part 1 requires you to sum all of the metadata objects.
[ "Part", "1", "requires", "you", "to", "sum", "all", "of", "the", "metadata", "objects", "." ]
[ "\"\"\"\n Part 1 requires you to sum all of the metadata objects. I do this with the recursive\n traverse_sum function.\n \"\"\"", "\"\"\"\n Compute the sum of a given node by summing all of all of the metadata values and\n adding the sum of all of the recursive calls to traverse_sum for al...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
b33bb324c04b3e52533f0d258edfadc323219e22
sumnerevans/advent-of-code
2018/08.py
[ "MIT" ]
Python
traverse_sum
<not_specific>
def traverse_sum(node): """ Compute the sum of a given node by summing all of all of the metadata values and adding the sum of all of the recursive calls to traverse_sum for all of the child nodes. """ return sum(node[1]) + sum(map(traverse_sum, node[0]))
Compute the sum of a given node by summing all of all of the metadata values and adding the sum of all of the recursive calls to traverse_sum for all of the child nodes.
Compute the sum of a given node by summing all of all of the metadata values and adding the sum of all of the recursive calls to traverse_sum for all of the child nodes.
[ "Compute", "the", "sum", "of", "a", "given", "node", "by", "summing", "all", "of", "all", "of", "the", "metadata", "values", "and", "adding", "the", "sum", "of", "all", "of", "the", "recursive", "calls", "to", "traverse_sum", "for", "all", "of", "the", ...
def traverse_sum(node): return sum(node[1]) + sum(map(traverse_sum, node[0]))
[ "def", "traverse_sum", "(", "node", ")", ":", "return", "sum", "(", "node", "[", "1", "]", ")", "+", "sum", "(", "map", "(", "traverse_sum", ",", "node", "[", "0", "]", ")", ")" ]
Compute the sum of a given node by summing all of all of the metadata values and adding the sum of all of the recursive calls to traverse_sum for all of the child nodes.
[ "Compute", "the", "sum", "of", "a", "given", "node", "by", "summing", "all", "of", "all", "of", "the", "metadata", "values", "and", "adding", "the", "sum", "of", "all", "of", "the", "recursive", "calls", "to", "traverse_sum", "for", "all", "of", "the", ...
[ "\"\"\"\n Compute the sum of a given node by summing all of all of the metadata values and\n adding the sum of all of the recursive calls to traverse_sum for all of the\n child nodes.\n \"\"\"" ]
[ { "param": "node", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "node", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b33bb324c04b3e52533f0d258edfadc323219e22
sumnerevans/advent-of-code
2018/08.py
[ "MIT" ]
Python
part2
int
def part2() -> int: """ Part 2 requires is very similar, but has a few different rules for the sum calculation. """ def traverse_sum(node): s = 0 if len(node[0]) == 0: # If a node has no child nodes, its value is the sum of its metadata # entries. ...
Part 2 requires is very similar, but has a few different rules for the sum calculation.
Part 2 requires is very similar, but has a few different rules for the sum calculation.
[ "Part", "2", "requires", "is", "very", "similar", "but", "has", "a", "few", "different", "rules", "for", "the", "sum", "calculation", "." ]
def part2() -> int: def traverse_sum(node): s = 0 if len(node[0]) == 0: return sum(node[1]) else: for mid in node[1]: if 0 < mid <= len(node[0]): s += traverse_sum(node[0][mid - 1]) return s return traverse_sum(TREE)
[ "def", "part2", "(", ")", "->", "int", ":", "def", "traverse_sum", "(", "node", ")", ":", "s", "=", "0", "if", "len", "(", "node", "[", "0", "]", ")", "==", "0", ":", "return", "sum", "(", "node", "[", "1", "]", ")", "else", ":", "for", "mi...
Part 2 requires is very similar, but has a few different rules for the sum calculation.
[ "Part", "2", "requires", "is", "very", "similar", "but", "has", "a", "few", "different", "rules", "for", "the", "sum", "calculation", "." ]
[ "\"\"\"\n Part 2 requires is very similar, but has a few different rules for the sum\n calculation.\n \"\"\"", "# If a node has no child nodes, its value is the sum of its metadata", "# entries.", "# However, if a node does have child nodes, the metadata entries become", "# indexes which refer to t...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
25f08fb61bcb4677b4cba4344a3ba378ec61241a
sumnerevans/advent-of-code
2020/23.py
[ "MIT" ]
Python
part2
<not_specific>
def part2(): """ The first key insight is that there are three operations for each iteration that all need to be constant time. 1. Remove the three elements to the right of current. 2. Finding the destination element. 3. Inserting the three picked elements once the destination is found. At...
The first key insight is that there are three operations for each iteration that all need to be constant time. 1. Remove the three elements to the right of current. 2. Finding the destination element. 3. Inserting the three picked elements once the destination is found. At first I attempted t...
The first key insight is that there are three operations for each iteration that all need to be constant time. 1. Remove the three elements to the right of current. 2. Finding the destination element. 3. Inserting the three picked elements once the destination is found. At first I attempted to implement all of this u...
[ "The", "first", "key", "insight", "is", "that", "there", "are", "three", "operations", "for", "each", "iteration", "that", "all", "need", "to", "be", "constant", "time", ".", "1", ".", "Remove", "the", "three", "elements", "to", "the", "right", "of", "cu...
def part2(): MAX_2 = 1_000_000 cups = deepcopy(CUPS) + [i for i in range(MAX_CUP + 1, MAX_2 + 1)] linked_list = {} for x, y in zip(cups, cups[1:]): linked_list[x] = y linked_list[cups[-1]] = cups[0] current = cups[0] for i in range(10_000_000): if debug and i % 10_000 == ...
[ "def", "part2", "(", ")", ":", "MAX_2", "=", "1_000_000", "cups", "=", "deepcopy", "(", "CUPS", ")", "+", "[", "i", "for", "i", "in", "range", "(", "MAX_CUP", "+", "1", ",", "MAX_2", "+", "1", ")", "]", "linked_list", "=", "{", "}", "for", "x",...
The first key insight is that there are three operations for each iteration that all need to be constant time.
[ "The", "first", "key", "insight", "is", "that", "there", "are", "three", "operations", "for", "each", "iteration", "that", "all", "need", "to", "be", "constant", "time", "." ]
[ "\"\"\"\n The first key insight is that there are three operations for each iteration that all\n need to be constant time.\n\n 1. Remove the three elements to the right of current.\n 2. Finding the destination element.\n 3. Inserting the three picked elements once the destination is found.\n\n At ...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
530b63c1bfe2402ab59239f1b9c085d4c63402d0
sumnerevans/advent-of-code
2020/18.py
[ "MIT" ]
Python
compute
Tuple[int, int]
def compute(tokens, i) -> Tuple[int, int]: """ Parameters: tokens: is the list of tokens i: the index to start computing at Returns: A tuple of the computation result up to the next end parentheses, and the index at which we finished computing. """ # This is a really dumb way of imp...
Parameters: tokens: is the list of tokens i: the index to start computing at Returns: A tuple of the computation result up to the next end parentheses, and the index at which we finished computing.
A tuple of the computation result up to the next end parentheses, and the index at which we finished computing.
[ "A", "tuple", "of", "the", "computation", "result", "up", "to", "the", "next", "end", "parentheses", "and", "the", "index", "at", "which", "we", "finished", "computing", "." ]
def compute(tokens, i) -> Tuple[int, int]: ismul = False isadd = False x = 0 while i < len(tokens): t = tokens[i] if isinstance(t, int) or t == "(": if t == "(": t, i = compute(tokens, i + 1) if ismul: x *= t ismul =...
[ "def", "compute", "(", "tokens", ",", "i", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "ismul", "=", "False", "isadd", "=", "False", "x", "=", "0", "while", "i", "<", "len", "(", "tokens", ")", ":", "t", "=", "tokens", "[", "i", "]"...
Parameters: tokens: is the list of tokens i: the index to start computing at
[ "Parameters", ":", "tokens", ":", "is", "the", "list", "of", "tokens", "i", ":", "the", "index", "to", "start", "computing", "at" ]
[ "\"\"\"\n Parameters:\n tokens: is the list of tokens\n i: the index to start computing at\n\n Returns:\n A tuple of the computation result up to the next end parentheses, and the index at\n which we finished computing.\n \"\"\"", "# This is a really dumb way of implicitly navigating the AST....
[ { "param": "tokens", "type": null }, { "param": "i", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tokens", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "i", "type": null, "docstring": null, "docstring_tokens": []...
530b63c1bfe2402ab59239f1b9c085d4c63402d0
sumnerevans/advent-of-code
2020/18.py
[ "MIT" ]
Python
addmul
<not_specific>
def addmul(terms): """ Perform addition on all of the terms that need to be added and then do the multiplication. This isn't the cleanest solution, but it was effective. """ while len(terms) > 1: if any(t == "+" for t in terms): for i in range...
Perform addition on all of the terms that need to be added and then do the multiplication. This isn't the cleanest solution, but it was effective.
Perform addition on all of the terms that need to be added and then do the multiplication. This isn't the cleanest solution, but it was effective.
[ "Perform", "addition", "on", "all", "of", "the", "terms", "that", "need", "to", "be", "added", "and", "then", "do", "the", "multiplication", ".", "This", "isn", "'", "t", "the", "cleanest", "solution", "but", "it", "was", "effective", "." ]
def addmul(terms): while len(terms) > 1: if any(t == "+" for t in terms): for i in range(len(terms)): if terms[i] == "+": new = terms[i - 1] + terms[i + 1] terms = terms[: i - 1] + [new] + terms[i + 2 :] ...
[ "def", "addmul", "(", "terms", ")", ":", "while", "len", "(", "terms", ")", ">", "1", ":", "if", "any", "(", "t", "==", "\"+\"", "for", "t", "in", "terms", ")", ":", "for", "i", "in", "range", "(", "len", "(", "terms", ")", ")", ":", "if", ...
Perform addition on all of the terms that need to be added and then do the multiplication.
[ "Perform", "addition", "on", "all", "of", "the", "terms", "that", "need", "to", "be", "added", "and", "then", "do", "the", "multiplication", "." ]
[ "\"\"\"\n Perform addition on all of the terms that need to be added and then do the\n multiplication.\n\n This isn't the cleanest solution, but it was effective.\n \"\"\"" ]
[ { "param": "terms", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "terms", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
379377949812dc39b1bb28ae860cb9ef490e0828
sumnerevans/advent-of-code
2020/17.py
[ "MIT" ]
Python
part2
int
def part2() -> int: """ Part 2 is the same as part 1, execpt for an added dimension. Each of the 6 iterations is O(n^4) where n is the max dimension in any direction. """ actives = set() for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c]: ...
Part 2 is the same as part 1, execpt for an added dimension. Each of the 6 iterations is O(n^4) where n is the max dimension in any direction.
Part 2 is the same as part 1, execpt for an added dimension. Each of the 6 iterations is O(n^4) where n is the max dimension in any direction.
[ "Part", "2", "is", "the", "same", "as", "part", "1", "execpt", "for", "an", "added", "dimension", ".", "Each", "of", "the", "6", "iterations", "is", "O", "(", "n^4", ")", "where", "n", "is", "the", "max", "dimension", "in", "any", "direction", "." ]
def part2() -> int: actives = set() for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c]: actives.add((r, c, 0, 0)) for _ in range(6): newactives = set(deepcopy(actives)) minR, maxR = seqminmax(a[0] for a in actives) minC, maxC = ...
[ "def", "part2", "(", ")", "->", "int", ":", "actives", "=", "set", "(", ")", "for", "r", "in", "range", "(", "len", "(", "grid", ")", ")", ":", "for", "c", "in", "range", "(", "len", "(", "grid", "[", "0", "]", ")", ")", ":", "if", "grid", ...
Part 2 is the same as part 1, execpt for an added dimension.
[ "Part", "2", "is", "the", "same", "as", "part", "1", "execpt", "for", "an", "added", "dimension", "." ]
[ "\"\"\"\n Part 2 is the same as part 1, execpt for an added dimension.\n Each of the 6 iterations is O(n^4) where n is the max dimension in any direction.\n \"\"\"", "# the cell is active" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
e1761e1b67ea120f71447b8c6eb6a3c550241643
sumnerevans/advent-of-code
2020/13.py
[ "MIT" ]
Python
part2_old
<not_specific>
def part2_old(): """ This was my first attempt. It is a brute-force algorithm, which clearly doesn't work because the input is to big. It does solve the samples, though. """ busses = [] gaps = [0] for b in lines[1].split(","): if b == "x": gaps[-1] += 1 contin...
This was my first attempt. It is a brute-force algorithm, which clearly doesn't work because the input is to big. It does solve the samples, though.
This was my first attempt. It is a brute-force algorithm, which clearly doesn't work because the input is to big. It does solve the samples, though.
[ "This", "was", "my", "first", "attempt", ".", "It", "is", "a", "brute", "-", "force", "algorithm", "which", "clearly", "doesn", "'", "t", "work", "because", "the", "input", "is", "to", "big", ".", "It", "does", "solve", "the", "samples", "though", "." ...
def part2_old(): busses = [] gaps = [0] for b in lines[1].split(","): if b == "x": gaps[-1] += 1 continue else: gaps.append(1) busses.append(int(b)) i = busses[0] k = 0 while True: if k % 100000 == 0: print(i) ...
[ "def", "part2_old", "(", ")", ":", "busses", "=", "[", "]", "gaps", "=", "[", "0", "]", "for", "b", "in", "lines", "[", "1", "]", ".", "split", "(", "\",\"", ")", ":", "if", "b", "==", "\"x\"", ":", "gaps", "[", "-", "1", "]", "+=", "1", ...
This was my first attempt.
[ "This", "was", "my", "first", "attempt", "." ]
[ "\"\"\"\n This was my first attempt. It is a brute-force algorithm, which clearly doesn't work\n because the input is to big. It does solve the samples, though.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
e1761e1b67ea120f71447b8c6eb6a3c550241643
sumnerevans/advent-of-code
2020/13.py
[ "MIT" ]
Python
extended_gcd
<not_specific>
def extended_gcd(a, b): """ I don't claim any copyright on this. I copied it from the internet somewhere. Extended Greatest Common Divisor Algorithm. Returns: gcd: The greatest common divisor of a and b. s, t: Coefficients such that s*a + t*b = gcd Reference: https://en.wi...
I don't claim any copyright on this. I copied it from the internet somewhere. Extended Greatest Common Divisor Algorithm. Returns: gcd: The greatest common divisor of a and b. s, t: Coefficients such that s*a + t*b = gcd Reference: https://en.wikipedia.org/wiki/Extended_Eucli...
I don't claim any copyright on this. I copied it from the internet somewhere. Extended Greatest Common Divisor Algorithm.
[ "I", "don", "'", "t", "claim", "any", "copyright", "on", "this", ".", "I", "copied", "it", "from", "the", "internet", "somewhere", ".", "Extended", "Greatest", "Common", "Divisor", "Algorithm", "." ]
def extended_gcd(a, b): old_r, r = a, b old_s, s = 1, 0 old_t, t = 0, 1 while r: quotient, remainder = divmod(old_r, r) old_r, r = r, remainder old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t return old_r, old_s, old_t
[ "def", "extended_gcd", "(", "a", ",", "b", ")", ":", "old_r", ",", "r", "=", "a", ",", "b", "old_s", ",", "s", "=", "1", ",", "0", "old_t", ",", "t", "=", "0", ",", "1", "while", "r", ":", "quotient", ",", "remainder", "=", "divmod", "(", "...
I don't claim any copyright on this.
[ "I", "don", "'", "t", "claim", "any", "copyright", "on", "this", "." ]
[ "\"\"\"\n I don't claim any copyright on this. I copied it from the internet somewhere.\n\n Extended Greatest Common Divisor Algorithm.\n\n Returns:\n gcd: The greatest common divisor of a and b.\n s, t: Coefficients such that s*a + t*b = gcd\n\n Reference:\n https://en.wikipedia.or...
[ { "param": "a", "type": null }, { "param": "b", "type": null } ]
{ "returns": [ { "docstring": "The greatest common divisor of a and b.\ns, t: Coefficients such that s*a + t*b = gcd", "docstring_tokens": [ "The", "greatest", "common", "divisor", "of", "a", "and", "b", ".", "s", ...
e1761e1b67ea120f71447b8c6eb6a3c550241643
sumnerevans/advent-of-code
2020/13.py
[ "MIT" ]
Python
combine_phased_rotations
<not_specific>
def combine_phased_rotations(a_period, a_phase, b_period, b_phase): """ I don't claim any copyright on this. I copied it from the internet somewhere. Combine two phased rotations into a single phased rotation Returns: combined_period, combined_phase The combined rotation is at its reference point...
I don't claim any copyright on this. I copied it from the internet somewhere. Combine two phased rotations into a single phased rotation Returns: combined_period, combined_phase The combined rotation is at its reference point if and only if both a and b are at their reference points.
I don't claim any copyright on this. I copied it from the internet somewhere. Combine two phased rotations into a single phased rotation The combined rotation is at its reference point if and only if both a and b are at their reference points.
[ "I", "don", "'", "t", "claim", "any", "copyright", "on", "this", ".", "I", "copied", "it", "from", "the", "internet", "somewhere", ".", "Combine", "two", "phased", "rotations", "into", "a", "single", "phased", "rotation", "The", "combined", "rotation", "is...
def combine_phased_rotations(a_period, a_phase, b_period, b_phase): gcd, s, _ = extended_gcd(a_period, b_period) phase_difference = a_phase - b_phase pd_mult, pd_remainder = divmod(phase_difference, gcd) if pd_remainder: raise ValueError("Rotation reference points never synchronize.") combin...
[ "def", "combine_phased_rotations", "(", "a_period", ",", "a_phase", ",", "b_period", ",", "b_phase", ")", ":", "gcd", ",", "s", ",", "_", "=", "extended_gcd", "(", "a_period", ",", "b_period", ")", "phase_difference", "=", "a_phase", "-", "b_phase", "pd_mult...
I don't claim any copyright on this.
[ "I", "don", "'", "t", "claim", "any", "copyright", "on", "this", "." ]
[ "\"\"\"\n I don't claim any copyright on this. I copied it from the internet somewhere.\n\n Combine two phased rotations into a single phased rotation\n\n Returns: combined_period, combined_phase\n\n The combined rotation is at its reference point if and only if both a and b\n are at their reference ...
[ { "param": "a_period", "type": null }, { "param": "a_phase", "type": null }, { "param": "b_period", "type": null }, { "param": "b_phase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "a_period", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "a_phase", "type": null, "docstring": null, "docstring_tok...
e1761e1b67ea120f71447b8c6eb6a3c550241643
sumnerevans/advent-of-code
2020/13.py
[ "MIT" ]
Python
part2_2
<not_specific>
def part2_2(): """ This was my second attempt. It's slightly more intelligent as it uses the smallest and largest bus IDs to calculate a larger step. This would have worked if I also had the additional insight that I needed to then use that to bootstrap finding how each subsequent bus lines up by i...
This was my second attempt. It's slightly more intelligent as it uses the smallest and largest bus IDs to calculate a larger step. This would have worked if I also had the additional insight that I needed to then use that to bootstrap finding how each subsequent bus lines up by iterating until I g...
This was my second attempt. It's slightly more intelligent as it uses the smallest and largest bus IDs to calculate a larger step. This would have worked if I also had the additional insight that I needed to then use that to bootstrap finding how each subsequent bus lines up by iterating until I got to a point where a...
[ "This", "was", "my", "second", "attempt", ".", "It", "'", "s", "slightly", "more", "intelligent", "as", "it", "uses", "the", "smallest", "and", "largest", "bus", "IDs", "to", "calculate", "a", "larger", "step", ".", "This", "would", "have", "worked", "if...
def part2_2(): busses = [] gaps = [0] for b in lines[1].split(","): if b == "x": gaps[-1] += 1 continue else: gaps.append(1) busses.append(int(b)) max_bus = 0 min_bus = INF max_bus_i = 0 min_bus_i = 0 for i, b in enumerate(b...
[ "def", "part2_2", "(", ")", ":", "busses", "=", "[", "]", "gaps", "=", "[", "0", "]", "for", "b", "in", "lines", "[", "1", "]", ".", "split", "(", "\",\"", ")", ":", "if", "b", "==", "\"x\"", ":", "gaps", "[", "-", "1", "]", "+=", "1", "c...
This was my second attempt.
[ "This", "was", "my", "second", "attempt", "." ]
[ "\"\"\"\n This was my second attempt. It's slightly more intelligent as it uses the smallest\n and largest bus IDs to calculate a larger step.\n\n This would have worked if I also had the additional insight that I needed to then\n use that to bootstrap finding how each subsequent bus lines up by iterati...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
e1761e1b67ea120f71447b8c6eb6a3c550241643
sumnerevans/advent-of-code
2020/13.py
[ "MIT" ]
Python
part2_3
<not_specific>
def part2_3(): """ Third attempt. This one I tried to implement the Chinese Remainder Theorem by hand. I failed. """ print(lines[1].split(",")) busses = [] gaps = [0] for b in lines[1].split(","): if b == "x": gaps[-1] += 1 continue else: ...
Third attempt. This one I tried to implement the Chinese Remainder Theorem by hand. I failed.
Third attempt. This one I tried to implement the Chinese Remainder Theorem by hand. I failed.
[ "Third", "attempt", ".", "This", "one", "I", "tried", "to", "implement", "the", "Chinese", "Remainder", "Theorem", "by", "hand", ".", "I", "failed", "." ]
def part2_3(): print(lines[1].split(",")) busses = [] gaps = [0] for b in lines[1].split(","): if b == "x": gaps[-1] += 1 continue else: gaps.append(1) busses.append(int(b)) N = reduce(lambda a, b: a * b, busses, 1) print(N) x =...
[ "def", "part2_3", "(", ")", ":", "print", "(", "lines", "[", "1", "]", ".", "split", "(", "\",\"", ")", ")", "busses", "=", "[", "]", "gaps", "=", "[", "0", "]", "for", "b", "in", "lines", "[", "1", "]", ".", "split", "(", "\",\"", ")", ":"...
Third attempt.
[ "Third", "attempt", "." ]
[ "\"\"\"\n Third attempt. This one I tried to implement the Chinese Remainder Theorem by hand.\n I failed.\n \"\"\"", "# (1/y_i) % sum(gaps[:i+1])" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }