repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ihabunek/toot
toot/wcstring.py
pad
def pad(text, length): """Pads text to given length, taking into account wide characters.""" text_length = wcswidth(text) if text_length < length: return text + ' ' * (length - text_length) return text
python
def pad(text, length): """Pads text to given length, taking into account wide characters.""" text_length = wcswidth(text) if text_length < length: return text + ' ' * (length - text_length) return text
[ "def", "pad", "(", "text", ",", "length", ")", ":", "text_length", "=", "wcswidth", "(", "text", ")", "if", "text_length", "<", "length", ":", "return", "text", "+", "' '", "*", "(", "length", "-", "text_length", ")", "return", "text" ]
Pads text to given length, taking into account wide characters.
[ "Pads", "text", "to", "given", "length", "taking", "into", "account", "wide", "characters", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L101-L108
train
230,700
ihabunek/toot
toot/wcstring.py
fit_text
def fit_text(text, length): """Makes text fit the given length by padding or truncating it.""" text_length = wcswidth(text) if text_length > length: return trunc(text, length) if text_length < length: return pad(text, length) return text
python
def fit_text(text, length): """Makes text fit the given length by padding or truncating it.""" text_length = wcswidth(text) if text_length > length: return trunc(text, length) if text_length < length: return pad(text, length) return text
[ "def", "fit_text", "(", "text", ",", "length", ")", ":", "text_length", "=", "wcswidth", "(", "text", ")", "if", "text_length", ">", "length", ":", "return", "trunc", "(", "text", ",", "length", ")", "if", "text_length", "<", "length", ":", "return", "...
Makes text fit the given length by padding or truncating it.
[ "Makes", "text", "fit", "the", "given", "length", "by", "padding", "or", "truncating", "it", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L111-L121
train
230,701
ihabunek/toot
toot/http.py
_get_error_message
def _get_error_message(response): """Attempt to extract an error message from response body""" try: data = response.json() if "error_description" in data: return data['error_description'] if "error" in data: return data['error'] except Exception: pass return "Unknown error"
python
def _get_error_message(response): """Attempt to extract an error message from response body""" try: data = response.json() if "error_description" in data: return data['error_description'] if "error" in data: return data['error'] except Exception: pass return "Unknown error"
[ "def", "_get_error_message", "(", "response", ")", ":", "try", ":", "data", "=", "response", ".", "json", "(", ")", "if", "\"error_description\"", "in", "data", ":", "return", "data", "[", "'error_description'", "]", "if", "\"error\"", "in", "data", ":", "...
Attempt to extract an error message from response body
[ "Attempt", "to", "extract", "an", "error", "message", "from", "response", "body" ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/http.py#L19-L30
train
230,702
ihabunek/toot
toot/api.py
_get_next_path
def _get_next_path(headers): """Given timeline response headers, returns the path to the next batch""" links = headers.get('Link', '') matches = re.match('<([^>]+)>; rel="next"', links) if matches: parsed = urlparse(matches.group(1)) return "?".join([parsed.path, parsed.query])
python
def _get_next_path(headers): """Given timeline response headers, returns the path to the next batch""" links = headers.get('Link', '') matches = re.match('<([^>]+)>; rel="next"', links) if matches: parsed = urlparse(matches.group(1)) return "?".join([parsed.path, parsed.query])
[ "def", "_get_next_path", "(", "headers", ")", ":", "links", "=", "headers", ".", "get", "(", "'Link'", ",", "''", ")", "matches", "=", "re", ".", "match", "(", "'<([^>]+)>; rel=\"next\"'", ",", "links", ")", "if", "matches", ":", "parsed", "=", "urlparse...
Given timeline response headers, returns the path to the next batch
[ "Given", "timeline", "response", "headers", "returns", "the", "path", "to", "the", "next", "batch" ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/api.py#L160-L166
train
230,703
ihabunek/toot
toot/ui/app.py
TimelineApp.select_previous
def select_previous(self): """Move to the previous status in the timeline.""" self.footer.clear_message() if self.selected == 0: self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN) return old_index = self.selected new_index = self.selected - 1 self.selected = new_index self.redraw_after_selection_change(old_index, new_index)
python
def select_previous(self): """Move to the previous status in the timeline.""" self.footer.clear_message() if self.selected == 0: self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN) return old_index = self.selected new_index = self.selected - 1 self.selected = new_index self.redraw_after_selection_change(old_index, new_index)
[ "def", "select_previous", "(", "self", ")", ":", "self", ".", "footer", ".", "clear_message", "(", ")", "if", "self", ".", "selected", "==", "0", ":", "self", ".", "footer", ".", "draw_message", "(", "\"Cannot move beyond first toot.\"", ",", "Color", ".", ...
Move to the previous status in the timeline.
[ "Move", "to", "the", "previous", "status", "in", "the", "timeline", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L692-L704
train
230,704
ihabunek/toot
toot/ui/app.py
TimelineApp.select_next
def select_next(self): """Move to the next status in the timeline.""" self.footer.clear_message() old_index = self.selected new_index = self.selected + 1 # Load more statuses if no more are available if self.selected + 1 >= len(self.statuses): self.fetch_next() self.left.draw_statuses(self.statuses, self.selected, new_index - 1) self.draw_footer_status() self.selected = new_index self.redraw_after_selection_change(old_index, new_index)
python
def select_next(self): """Move to the next status in the timeline.""" self.footer.clear_message() old_index = self.selected new_index = self.selected + 1 # Load more statuses if no more are available if self.selected + 1 >= len(self.statuses): self.fetch_next() self.left.draw_statuses(self.statuses, self.selected, new_index - 1) self.draw_footer_status() self.selected = new_index self.redraw_after_selection_change(old_index, new_index)
[ "def", "select_next", "(", "self", ")", ":", "self", ".", "footer", ".", "clear_message", "(", ")", "old_index", "=", "self", ".", "selected", "new_index", "=", "self", ".", "selected", "+", "1", "# Load more statuses if no more are available", "if", "self", "...
Move to the next status in the timeline.
[ "Move", "to", "the", "next", "status", "in", "the", "timeline", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L706-L720
train
230,705
ihabunek/toot
toot/ui/app.py
TimelineApp.full_redraw
def full_redraw(self): """Perform a full redraw of the UI.""" self.left.draw_statuses(self.statuses, self.selected) self.right.draw(self.get_selected_status()) self.header.draw(self.user) self.draw_footer_status()
python
def full_redraw(self): """Perform a full redraw of the UI.""" self.left.draw_statuses(self.statuses, self.selected) self.right.draw(self.get_selected_status()) self.header.draw(self.user) self.draw_footer_status()
[ "def", "full_redraw", "(", "self", ")", ":", "self", ".", "left", ".", "draw_statuses", "(", "self", ".", "statuses", ",", "self", ".", "selected", ")", "self", ".", "right", ".", "draw", "(", "self", ".", "get_selected_status", "(", ")", ")", "self", ...
Perform a full redraw of the UI.
[ "Perform", "a", "full", "redraw", "of", "the", "UI", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L740-L746
train
230,706
ihabunek/toot
toot/ui/utils.py
size_as_drawn
def size_as_drawn(lines, screen_width): """Get the bottom-right corner of some text as would be drawn by draw_lines""" y = 0 x = 0 for line in lines: wrapped = list(wc_wrap(line, screen_width)) if len(wrapped) > 0: for wrapped_line in wrapped: x = len(wrapped_line) y += 1 else: x = 0 y += 1 return y - 1, x - 1 if x != 0 else 0
python
def size_as_drawn(lines, screen_width): """Get the bottom-right corner of some text as would be drawn by draw_lines""" y = 0 x = 0 for line in lines: wrapped = list(wc_wrap(line, screen_width)) if len(wrapped) > 0: for wrapped_line in wrapped: x = len(wrapped_line) y += 1 else: x = 0 y += 1 return y - 1, x - 1 if x != 0 else 0
[ "def", "size_as_drawn", "(", "lines", ",", "screen_width", ")", ":", "y", "=", "0", "x", "=", "0", "for", "line", "in", "lines", ":", "wrapped", "=", "list", "(", "wc_wrap", "(", "line", ",", "screen_width", ")", ")", "if", "len", "(", "wrapped", "...
Get the bottom-right corner of some text as would be drawn by draw_lines
[ "Get", "the", "bottom", "-", "right", "corner", "of", "some", "text", "as", "would", "be", "drawn", "by", "draw_lines" ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/utils.py#L49-L62
train
230,707
ihabunek/toot
toot/commands.py
_find_account
def _find_account(app, user, account_name): """For a given account name, returns the Account object. Raises an exception if not found. """ if not account_name: raise ConsoleError("Empty account name given") accounts = api.search_accounts(app, user, account_name) if account_name[0] == "@": account_name = account_name[1:] for account in accounts: if account['acct'] == account_name: return account raise ConsoleError("Account not found")
python
def _find_account(app, user, account_name): """For a given account name, returns the Account object. Raises an exception if not found. """ if not account_name: raise ConsoleError("Empty account name given") accounts = api.search_accounts(app, user, account_name) if account_name[0] == "@": account_name = account_name[1:] for account in accounts: if account['acct'] == account_name: return account raise ConsoleError("Account not found")
[ "def", "_find_account", "(", "app", ",", "user", ",", "account_name", ")", ":", "if", "not", "account_name", ":", "raise", "ConsoleError", "(", "\"Empty account name given\"", ")", "accounts", "=", "api", ".", "search_accounts", "(", "app", ",", "user", ",", ...
For a given account name, returns the Account object. Raises an exception if not found.
[ "For", "a", "given", "account", "name", "returns", "the", "Account", "object", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/commands.py#L216-L233
train
230,708
ihabunek/toot
toot/config_legacy.py
add_username
def add_username(user, apps): """When using broser login, username was not stored so look it up""" if not user: return None apps = [a for a in apps if a.instance == user.instance] if not apps: return None from toot.api import verify_credentials creds = verify_credentials(apps.pop(), user) return User(user.instance, creds['username'], user.access_token)
python
def add_username(user, apps): """When using broser login, username was not stored so look it up""" if not user: return None apps = [a for a in apps if a.instance == user.instance] if not apps: return None from toot.api import verify_credentials creds = verify_credentials(apps.pop(), user) return User(user.instance, creds['username'], user.access_token)
[ "def", "add_username", "(", "user", ",", "apps", ")", ":", "if", "not", "user", ":", "return", "None", "apps", "=", "[", "a", "for", "a", "in", "apps", "if", "a", ".", "instance", "==", "user", ".", "instance", "]", "if", "not", "apps", ":", "ret...
When using broser login, username was not stored so look it up
[ "When", "using", "broser", "login", "username", "was", "not", "stored", "so", "look", "it", "up" ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/config_legacy.py#L42-L55
train
230,709
ihabunek/toot
toot/utils.py
get_text
def get_text(html): """Converts html to text, strips all tags.""" # Ignore warnings made by BeautifulSoup, if passed something that looks like # a file (e.g. a dot which matches current dict), it will warn that the file # should be opened instead of passing a filename. with warnings.catch_warnings(): warnings.simplefilter("ignore") text = BeautifulSoup(html.replace('&apos;', "'"), "html.parser").get_text() return unicodedata.normalize('NFKC', text)
python
def get_text(html): """Converts html to text, strips all tags.""" # Ignore warnings made by BeautifulSoup, if passed something that looks like # a file (e.g. a dot which matches current dict), it will warn that the file # should be opened instead of passing a filename. with warnings.catch_warnings(): warnings.simplefilter("ignore") text = BeautifulSoup(html.replace('&apos;', "'"), "html.parser").get_text() return unicodedata.normalize('NFKC', text)
[ "def", "get_text", "(", "html", ")", ":", "# Ignore warnings made by BeautifulSoup, if passed something that looks like", "# a file (e.g. a dot which matches current dict), it will warn that the file", "# should be opened instead of passing a filename.", "with", "warnings", ".", "catch_warni...
Converts html to text, strips all tags.
[ "Converts", "html", "to", "text", "strips", "all", "tags", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L19-L29
train
230,710
ihabunek/toot
toot/utils.py
parse_html
def parse_html(html): """Attempt to convert html to plain text while keeping line breaks. Returns a list of paragraphs, each being a list of lines. """ paragraphs = re.split("</?p[^>]*>", html) # Convert <br>s to line breaks and remove empty paragraphs paragraphs = [re.split("<br */?>", p) for p in paragraphs if p] # Convert each line in each paragraph to plain text: return [[get_text(l) for l in p] for p in paragraphs]
python
def parse_html(html): """Attempt to convert html to plain text while keeping line breaks. Returns a list of paragraphs, each being a list of lines. """ paragraphs = re.split("</?p[^>]*>", html) # Convert <br>s to line breaks and remove empty paragraphs paragraphs = [re.split("<br */?>", p) for p in paragraphs if p] # Convert each line in each paragraph to plain text: return [[get_text(l) for l in p] for p in paragraphs]
[ "def", "parse_html", "(", "html", ")", ":", "paragraphs", "=", "re", ".", "split", "(", "\"</?p[^>]*>\"", ",", "html", ")", "# Convert <br>s to line breaks and remove empty paragraphs", "paragraphs", "=", "[", "re", ".", "split", "(", "\"<br */?>\"", ",", "p", "...
Attempt to convert html to plain text while keeping line breaks. Returns a list of paragraphs, each being a list of lines.
[ "Attempt", "to", "convert", "html", "to", "plain", "text", "while", "keeping", "line", "breaks", ".", "Returns", "a", "list", "of", "paragraphs", "each", "being", "a", "list", "of", "lines", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L32-L42
train
230,711
ihabunek/toot
toot/utils.py
format_content
def format_content(content): """Given a Status contents in HTML, converts it into lines of plain text. Returns a generator yielding lines of content. """ paragraphs = parse_html(content) first = True for paragraph in paragraphs: if not first: yield "" for line in paragraph: yield line first = False
python
def format_content(content): """Given a Status contents in HTML, converts it into lines of plain text. Returns a generator yielding lines of content. """ paragraphs = parse_html(content) first = True for paragraph in paragraphs: if not first: yield "" for line in paragraph: yield line first = False
[ "def", "format_content", "(", "content", ")", ":", "paragraphs", "=", "parse_html", "(", "content", ")", "first", "=", "True", "for", "paragraph", "in", "paragraphs", ":", "if", "not", "first", ":", "yield", "\"\"", "for", "line", "in", "paragraph", ":", ...
Given a Status contents in HTML, converts it into lines of plain text. Returns a generator yielding lines of content.
[ "Given", "a", "Status", "contents", "in", "HTML", "converts", "it", "into", "lines", "of", "plain", "text", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L45-L62
train
230,712
ihabunek/toot
toot/utils.py
multiline_input
def multiline_input(): """Lets user input multiple lines of text, terminated by EOF.""" lines = [] while True: try: lines.append(input()) except EOFError: break return "\n".join(lines).strip()
python
def multiline_input(): """Lets user input multiple lines of text, terminated by EOF.""" lines = [] while True: try: lines.append(input()) except EOFError: break return "\n".join(lines).strip()
[ "def", "multiline_input", "(", ")", ":", "lines", "=", "[", "]", "while", "True", ":", "try", ":", "lines", ".", "append", "(", "input", "(", ")", ")", "except", "EOFError", ":", "break", "return", "\"\\n\"", ".", "join", "(", "lines", ")", ".", "s...
Lets user input multiple lines of text, terminated by EOF.
[ "Lets", "user", "input", "multiple", "lines", "of", "text", "terminated", "by", "EOF", "." ]
d13fa8685b300f96621fa325774913ec0f413a7f
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L81-L90
train
230,713
Azure/azure-kusto-python
azure-kusto-data/azure/kusto/data/_models.py
KustoResultTable.to_dict
def to_dict(self): """Converts the table to a dict.""" return {"name": self.table_name, "kind": self.table_kind, "data": [r.to_dict() for r in self]}
python
def to_dict(self): """Converts the table to a dict.""" return {"name": self.table_name, "kind": self.table_kind, "data": [r.to_dict() for r in self]}
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "table_name", ",", "\"kind\"", ":", "self", ".", "table_kind", ",", "\"data\"", ":", "[", "r", ".", "to_dict", "(", ")", "for", "r", "in", "self", "]", "}" ]
Converts the table to a dict.
[ "Converts", "the", "table", "to", "a", "dict", "." ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/_models.py#L152-L154
train
230,714
Azure/azure-kusto-python
azure-kusto-data/azure/kusto/data/_converters.py
to_datetime
def to_datetime(value): """Converts a string to a datetime.""" if value is None: return None if isinstance(value, six.integer_types): return parser.parse(value) return parser.isoparse(value)
python
def to_datetime(value): """Converts a string to a datetime.""" if value is None: return None if isinstance(value, six.integer_types): return parser.parse(value) return parser.isoparse(value)
[ "def", "to_datetime", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", ":", "return", "parser", ".", "parse", "(", "value", ")", "return", "parser", "."...
Converts a string to a datetime.
[ "Converts", "a", "string", "to", "a", "datetime", "." ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/_converters.py#L12-L19
train
230,715
Azure/azure-kusto-python
azure-kusto-data/azure/kusto/data/_converters.py
to_timedelta
def to_timedelta(value): """Converts a string to a timedelta.""" if value is None: return None if isinstance(value, (six.integer_types, float)): return timedelta(microseconds=(float(value) / 10)) match = _TIMESPAN_PATTERN.match(value) if match: if match.group(1) == "-": factor = -1 else: factor = 1 return factor * timedelta( days=int(match.group("d") or 0), hours=int(match.group("h")), minutes=int(match.group("m")), seconds=float(match.group("s")), ) else: raise ValueError("Timespan value '{}' cannot be decoded".format(value))
python
def to_timedelta(value): """Converts a string to a timedelta.""" if value is None: return None if isinstance(value, (six.integer_types, float)): return timedelta(microseconds=(float(value) / 10)) match = _TIMESPAN_PATTERN.match(value) if match: if match.group(1) == "-": factor = -1 else: factor = 1 return factor * timedelta( days=int(match.group("d") or 0), hours=int(match.group("h")), minutes=int(match.group("m")), seconds=float(match.group("s")), ) else: raise ValueError("Timespan value '{}' cannot be decoded".format(value))
[ "def", "to_timedelta", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "six", ".", "integer_types", ",", "float", ")", ")", ":", "return", "timedelta", "(", "microseconds", "=", "(...
Converts a string to a timedelta.
[ "Converts", "a", "string", "to", "a", "timedelta", "." ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/_converters.py#L22-L41
train
230,716
Azure/azure-kusto-python
azure-kusto-data/azure/kusto/data/security.py
_AadHelper.acquire_authorization_header
def acquire_authorization_header(self): """Acquire tokens from AAD.""" try: return self._acquire_authorization_header() except AdalError as error: if self._authentication_method is AuthenticationMethod.aad_username_password: kwargs = {"username": self._username, "client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_application_key: kwargs = {"client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_device_login: kwargs = {"client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_application_certificate: kwargs = {"client_id": self._client_id, "thumbprint": self._thumbprint} else: raise error kwargs["resource"] = self._kusto_cluster kwargs["authority"] = self._adal_context.authority.url raise KustoAuthenticationError(self._authentication_method.value, error, **kwargs)
python
def acquire_authorization_header(self): """Acquire tokens from AAD.""" try: return self._acquire_authorization_header() except AdalError as error: if self._authentication_method is AuthenticationMethod.aad_username_password: kwargs = {"username": self._username, "client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_application_key: kwargs = {"client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_device_login: kwargs = {"client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_application_certificate: kwargs = {"client_id": self._client_id, "thumbprint": self._thumbprint} else: raise error kwargs["resource"] = self._kusto_cluster kwargs["authority"] = self._adal_context.authority.url raise KustoAuthenticationError(self._authentication_method.value, error, **kwargs)
[ "def", "acquire_authorization_header", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_acquire_authorization_header", "(", ")", "except", "AdalError", "as", "error", ":", "if", "self", ".", "_authentication_method", "is", "AuthenticationMethod", ".", "...
Acquire tokens from AAD.
[ "Acquire", "tokens", "from", "AAD", "." ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/security.py#L49-L68
train
230,717
Azure/azure-kusto-python
azure-kusto-data/azure/kusto/data/request.py
KustoClient._execute
def _execute(self, endpoint, database, query, default_timeout, properties=None): """Executes given query against this client""" request_payload = {"db": database, "csl": query} if properties: request_payload["properties"] = properties.to_json() request_headers = { "Accept": "application/json", "Accept-Encoding": "gzip,deflate", "Content-Type": "application/json; charset=utf-8", "x-ms-client-version": "Kusto.Python.Client:" + VERSION, "x-ms-client-request-id": "KPC.execute;" + str(uuid.uuid4()), } if self._auth_provider: request_headers["Authorization"] = self._auth_provider.acquire_authorization_header() timeout = self._get_timeout(properties, default_timeout) response = self._session.post(endpoint, headers=request_headers, json=request_payload, timeout=timeout.seconds) if response.status_code == 200: if endpoint.endswith("v2/rest/query"): return KustoResponseDataSetV2(response.json()) return KustoResponseDataSetV1(response.json()) raise KustoServiceError([response.json()], response)
python
def _execute(self, endpoint, database, query, default_timeout, properties=None): """Executes given query against this client""" request_payload = {"db": database, "csl": query} if properties: request_payload["properties"] = properties.to_json() request_headers = { "Accept": "application/json", "Accept-Encoding": "gzip,deflate", "Content-Type": "application/json; charset=utf-8", "x-ms-client-version": "Kusto.Python.Client:" + VERSION, "x-ms-client-request-id": "KPC.execute;" + str(uuid.uuid4()), } if self._auth_provider: request_headers["Authorization"] = self._auth_provider.acquire_authorization_header() timeout = self._get_timeout(properties, default_timeout) response = self._session.post(endpoint, headers=request_headers, json=request_payload, timeout=timeout.seconds) if response.status_code == 200: if endpoint.endswith("v2/rest/query"): return KustoResponseDataSetV2(response.json()) return KustoResponseDataSetV1(response.json()) raise KustoServiceError([response.json()], response)
[ "def", "_execute", "(", "self", ",", "endpoint", ",", "database", ",", "query", ",", "default_timeout", ",", "properties", "=", "None", ")", ":", "request_payload", "=", "{", "\"db\"", ":", "database", ",", "\"csl\"", ":", "query", "}", "if", "properties",...
Executes given query against this client
[ "Executes", "given", "query", "against", "this", "client" ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/request.py#L360-L386
train
230,718
Azure/azure-kusto-python
azure-kusto-data/azure/kusto/data/request.py
ClientRequestProperties.set_option
def set_option(self, name, value): """Sets an option's value""" _assert_value_is_valid(name) self._options[name] = value
python
def set_option(self, name, value): """Sets an option's value""" _assert_value_is_valid(name) self._options[name] = value
[ "def", "set_option", "(", "self", ",", "name", ",", "value", ")", ":", "_assert_value_is_valid", "(", "name", ")", "self", ".", "_options", "[", "name", "]", "=", "value" ]
Sets an option's value
[ "Sets", "an", "option", "s", "value" ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/request.py#L467-L470
train
230,719
Azure/azure-kusto-python
azure-kusto-ingest/azure/kusto/ingest/_resource_manager.py
_ResourceUri.parse
def parse(cls, uri): """Parses uri into a ResourceUri object""" match = _URI_FORMAT.search(uri) return cls(match.group(1), match.group(2), match.group(3), match.group(4))
python
def parse(cls, uri): """Parses uri into a ResourceUri object""" match = _URI_FORMAT.search(uri) return cls(match.group(1), match.group(2), match.group(3), match.group(4))
[ "def", "parse", "(", "cls", ",", "uri", ")", ":", "match", "=", "_URI_FORMAT", ".", "search", "(", "uri", ")", "return", "cls", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ",", "match", ".", "group", "(...
Parses uri into a ResourceUri object
[ "Parses", "uri", "into", "a", "ResourceUri", "object" ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-ingest/azure/kusto/ingest/_resource_manager.py#L17-L20
train
230,720
Azure/azure-kusto-python
azure-kusto-ingest/azure/kusto/ingest/_ingestion_properties.py
IngestionProperties.get_mapping_format
def get_mapping_format(self): """Dictating the corresponding mapping to the format.""" if self.format == DataFormat.json or self.format == DataFormat.avro: return self.format.name else: return DataFormat.csv.name
python
def get_mapping_format(self): """Dictating the corresponding mapping to the format.""" if self.format == DataFormat.json or self.format == DataFormat.avro: return self.format.name else: return DataFormat.csv.name
[ "def", "get_mapping_format", "(", "self", ")", ":", "if", "self", ".", "format", "==", "DataFormat", ".", "json", "or", "self", ".", "format", "==", "DataFormat", ".", "avro", ":", "return", "self", ".", "format", ".", "name", "else", ":", "return", "D...
Dictating the corresponding mapping to the format.
[ "Dictating", "the", "corresponding", "mapping", "to", "the", "format", "." ]
92466a2ae175d6353d1dee3496a02517b2a71a86
https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-ingest/azure/kusto/ingest/_ingestion_properties.py#L125-L130
train
230,721
yuce/pyswip
pyswip/easy.py
getAtomChars
def getAtomChars(t): """If t is an atom, return it as a string, otherwise raise InvalidTypeError. """ s = c_char_p() if PL_get_atom_chars(t, byref(s)): return s.value else: raise InvalidTypeError("atom")
python
def getAtomChars(t): """If t is an atom, return it as a string, otherwise raise InvalidTypeError. """ s = c_char_p() if PL_get_atom_chars(t, byref(s)): return s.value else: raise InvalidTypeError("atom")
[ "def", "getAtomChars", "(", "t", ")", ":", "s", "=", "c_char_p", "(", ")", "if", "PL_get_atom_chars", "(", "t", ",", "byref", "(", "s", ")", ")", ":", "return", "s", ".", "value", "else", ":", "raise", "InvalidTypeError", "(", "\"atom\"", ")" ]
If t is an atom, return it as a string, otherwise raise InvalidTypeError.
[ "If", "t", "is", "an", "atom", "return", "it", "as", "a", "string", "otherwise", "raise", "InvalidTypeError", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L333-L340
train
230,722
yuce/pyswip
pyswip/easy.py
getBool
def getBool(t): """If t is of type bool, return it, otherwise raise InvalidTypeError. """ b = c_int() if PL_get_long(t, byref(b)): return bool(b.value) else: raise InvalidTypeError("bool")
python
def getBool(t): """If t is of type bool, return it, otherwise raise InvalidTypeError. """ b = c_int() if PL_get_long(t, byref(b)): return bool(b.value) else: raise InvalidTypeError("bool")
[ "def", "getBool", "(", "t", ")", ":", "b", "=", "c_int", "(", ")", "if", "PL_get_long", "(", "t", ",", "byref", "(", "b", ")", ")", ":", "return", "bool", "(", "b", ".", "value", ")", "else", ":", "raise", "InvalidTypeError", "(", "\"bool\"", ")"...
If t is of type bool, return it, otherwise raise InvalidTypeError.
[ "If", "t", "is", "of", "type", "bool", "return", "it", "otherwise", "raise", "InvalidTypeError", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L349-L356
train
230,723
yuce/pyswip
pyswip/easy.py
getLong
def getLong(t): """If t is of type long, return it, otherwise raise InvalidTypeError. """ i = c_long() if PL_get_long(t, byref(i)): return i.value else: raise InvalidTypeError("long")
python
def getLong(t): """If t is of type long, return it, otherwise raise InvalidTypeError. """ i = c_long() if PL_get_long(t, byref(i)): return i.value else: raise InvalidTypeError("long")
[ "def", "getLong", "(", "t", ")", ":", "i", "=", "c_long", "(", ")", "if", "PL_get_long", "(", "t", ",", "byref", "(", "i", ")", ")", ":", "return", "i", ".", "value", "else", ":", "raise", "InvalidTypeError", "(", "\"long\"", ")" ]
If t is of type long, return it, otherwise raise InvalidTypeError.
[ "If", "t", "is", "of", "type", "long", "return", "it", "otherwise", "raise", "InvalidTypeError", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L359-L366
train
230,724
yuce/pyswip
pyswip/easy.py
getFloat
def getFloat(t): """If t is of type float, return it, otherwise raise InvalidTypeError. """ d = c_double() if PL_get_float(t, byref(d)): return d.value else: raise InvalidTypeError("float")
python
def getFloat(t): """If t is of type float, return it, otherwise raise InvalidTypeError. """ d = c_double() if PL_get_float(t, byref(d)): return d.value else: raise InvalidTypeError("float")
[ "def", "getFloat", "(", "t", ")", ":", "d", "=", "c_double", "(", ")", "if", "PL_get_float", "(", "t", ",", "byref", "(", "d", ")", ")", ":", "return", "d", ".", "value", "else", ":", "raise", "InvalidTypeError", "(", "\"float\"", ")" ]
If t is of type float, return it, otherwise raise InvalidTypeError.
[ "If", "t", "is", "of", "type", "float", "return", "it", "otherwise", "raise", "InvalidTypeError", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L372-L379
train
230,725
yuce/pyswip
pyswip/easy.py
getString
def getString(t): """If t is of type string, return it, otherwise raise InvalidTypeError. """ slen = c_int() s = c_char_p() if PL_get_string_chars(t, byref(s), byref(slen)): return s.value else: raise InvalidTypeError("string")
python
def getString(t): """If t is of type string, return it, otherwise raise InvalidTypeError. """ slen = c_int() s = c_char_p() if PL_get_string_chars(t, byref(s), byref(slen)): return s.value else: raise InvalidTypeError("string")
[ "def", "getString", "(", "t", ")", ":", "slen", "=", "c_int", "(", ")", "s", "=", "c_char_p", "(", ")", "if", "PL_get_string_chars", "(", "t", ",", "byref", "(", "s", ")", ",", "byref", "(", "slen", ")", ")", ":", "return", "s", ".", "value", "...
If t is of type string, return it, otherwise raise InvalidTypeError.
[ "If", "t", "is", "of", "type", "string", "return", "it", "otherwise", "raise", "InvalidTypeError", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L382-L390
train
230,726
yuce/pyswip
pyswip/easy.py
getList
def getList(x): """ Return t as a list. """ t = PL_copy_term_ref(x) head = PL_new_term_ref() result = [] while PL_get_list(t, head, t): result.append(getTerm(head)) head = PL_new_term_ref() return result
python
def getList(x): """ Return t as a list. """ t = PL_copy_term_ref(x) head = PL_new_term_ref() result = [] while PL_get_list(t, head, t): result.append(getTerm(head)) head = PL_new_term_ref() return result
[ "def", "getList", "(", "x", ")", ":", "t", "=", "PL_copy_term_ref", "(", "x", ")", "head", "=", "PL_new_term_ref", "(", ")", "result", "=", "[", "]", "while", "PL_get_list", "(", "t", ",", "head", ",", "t", ")", ":", "result", ".", "append", "(", ...
Return t as a list.
[ "Return", "t", "as", "a", "list", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L411-L423
train
230,727
yuce/pyswip
pyswip/easy.py
Atom.fromTerm
def fromTerm(cls, term): """Create an atom from a Term or term handle.""" if isinstance(term, Term): term = term.handle elif not isinstance(term, (c_void_p, int)): raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term))) a = atom_t() if PL_get_atom(term, byref(a)): return cls(a.value)
python
def fromTerm(cls, term): """Create an atom from a Term or term handle.""" if isinstance(term, Term): term = term.handle elif not isinstance(term, (c_void_p, int)): raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term))) a = atom_t() if PL_get_atom(term, byref(a)): return cls(a.value)
[ "def", "fromTerm", "(", "cls", ",", "term", ")", ":", "if", "isinstance", "(", "term", ",", "Term", ")", ":", "term", "=", "term", ".", "handle", "elif", "not", "isinstance", "(", "term", ",", "(", "c_void_p", ",", "int", ")", ")", ":", "raise", ...
Create an atom from a Term or term handle.
[ "Create", "an", "atom", "from", "a", "Term", "or", "term", "handle", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L62-L72
train
230,728
yuce/pyswip
pyswip/easy.py
Functor.fromTerm
def fromTerm(cls, term): """Create a functor from a Term or term handle.""" if isinstance(term, Term): term = term.handle elif not isinstance(term, (c_void_p, int)): raise ArgumentTypeError((str(Term), str(int)), str(type(term))) f = functor_t() if PL_get_functor(term, byref(f)): # get args args = [] arity = PL_functor_arity(f.value) # let's have all args be consecutive a0 = PL_new_term_refs(arity) for i, a in enumerate(range(1, arity + 1)): if PL_get_arg(a, term, a0 + i): args.append(getTerm(a0 + i)) return cls(f.value, args=args, a0=a0)
python
def fromTerm(cls, term): """Create a functor from a Term or term handle.""" if isinstance(term, Term): term = term.handle elif not isinstance(term, (c_void_p, int)): raise ArgumentTypeError((str(Term), str(int)), str(type(term))) f = functor_t() if PL_get_functor(term, byref(f)): # get args args = [] arity = PL_functor_arity(f.value) # let's have all args be consecutive a0 = PL_new_term_refs(arity) for i, a in enumerate(range(1, arity + 1)): if PL_get_arg(a, term, a0 + i): args.append(getTerm(a0 + i)) return cls(f.value, args=args, a0=a0)
[ "def", "fromTerm", "(", "cls", ",", "term", ")", ":", "if", "isinstance", "(", "term", ",", "Term", ")", ":", "term", "=", "term", ".", "handle", "elif", "not", "isinstance", "(", "term", ",", "(", "c_void_p", ",", "int", ")", ")", ":", "raise", ...
Create a functor from a Term or term handle.
[ "Create", "a", "functor", "from", "a", "Term", "or", "term", "handle", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L235-L254
train
230,729
yuce/pyswip
pyswip/core.py
_findSwiplWin
def _findSwiplWin(): import re """ This function uses several heuristics to gues where SWI-Prolog is installed in Windows. It always returns None as the path of the resource file because, in Windows, the way to find it is more robust so the SWI-Prolog DLL is always able to find it. :returns: A tuple of (path to the swipl DLL, path to the resource file) :returns type: ({str, None}, {str, None}) """ dllNames = ('swipl.dll', 'libswipl.dll') # First try: check the usual installation path (this is faster but # hardcoded) programFiles = os.getenv('ProgramFiles') paths = [os.path.join(programFiles, r'pl\bin', dllName) for dllName in dllNames] for path in paths: if os.path.exists(path): return (path, None) # Second try: use the find_library path = _findSwiplPathFromFindLib() if path is not None and os.path.exists(path): return (path, None) # Third try: use reg.exe to find the installation path in the registry # (reg should be installed in all Windows XPs) try: cmd = Popen(['reg', 'query', r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog', '/v', 'home'], stdout=PIPE) ret = cmd.communicate() # Result is like: # ! REG.EXE VERSION 3.0 # # HKEY_LOCAL_MACHINE\Software\SWI\Prolog # home REG_SZ C:\Program Files\pl # (Note: spaces may be \t or spaces in the output) ret = ret[0].splitlines() ret = [line.decode("utf-8") for line in ret if len(line) > 0] pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$') match = pattern.match(ret[-1]) if match is not None: path = match.group(2) paths = [os.path.join(path, 'bin', dllName) for dllName in dllNames] for path in paths: if os.path.exists(path): return (path, None) except OSError: # reg.exe not found? Weird... pass # May the exec is on path? (path, swiHome) = _findSwiplFromExec() if path is not None: return (path, swiHome) # Last try: maybe it is in the current dir for dllName in dllNames: if os.path.exists(dllName): return (dllName, None) return (None, None)
python
def _findSwiplWin(): import re """ This function uses several heuristics to gues where SWI-Prolog is installed in Windows. It always returns None as the path of the resource file because, in Windows, the way to find it is more robust so the SWI-Prolog DLL is always able to find it. :returns: A tuple of (path to the swipl DLL, path to the resource file) :returns type: ({str, None}, {str, None}) """ dllNames = ('swipl.dll', 'libswipl.dll') # First try: check the usual installation path (this is faster but # hardcoded) programFiles = os.getenv('ProgramFiles') paths = [os.path.join(programFiles, r'pl\bin', dllName) for dllName in dllNames] for path in paths: if os.path.exists(path): return (path, None) # Second try: use the find_library path = _findSwiplPathFromFindLib() if path is not None and os.path.exists(path): return (path, None) # Third try: use reg.exe to find the installation path in the registry # (reg should be installed in all Windows XPs) try: cmd = Popen(['reg', 'query', r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog', '/v', 'home'], stdout=PIPE) ret = cmd.communicate() # Result is like: # ! REG.EXE VERSION 3.0 # # HKEY_LOCAL_MACHINE\Software\SWI\Prolog # home REG_SZ C:\Program Files\pl # (Note: spaces may be \t or spaces in the output) ret = ret[0].splitlines() ret = [line.decode("utf-8") for line in ret if len(line) > 0] pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$') match = pattern.match(ret[-1]) if match is not None: path = match.group(2) paths = [os.path.join(path, 'bin', dllName) for dllName in dllNames] for path in paths: if os.path.exists(path): return (path, None) except OSError: # reg.exe not found? Weird... pass # May the exec is on path? (path, swiHome) = _findSwiplFromExec() if path is not None: return (path, swiHome) # Last try: maybe it is in the current dir for dllName in dllNames: if os.path.exists(dllName): return (dllName, None) return (None, None)
[ "def", "_findSwiplWin", "(", ")", ":", "import", "re", "dllNames", "=", "(", "'swipl.dll'", ",", "'libswipl.dll'", ")", "# First try: check the usual installation path (this is faster but", "# hardcoded)", "programFiles", "=", "os", ".", "getenv", "(", "'ProgramFiles'", ...
This function uses several heuristics to gues where SWI-Prolog is installed in Windows. It always returns None as the path of the resource file because, in Windows, the way to find it is more robust so the SWI-Prolog DLL is always able to find it. :returns: A tuple of (path to the swipl DLL, path to the resource file) :returns type: ({str, None}, {str, None})
[ "This", "function", "uses", "several", "heuristics", "to", "gues", "where", "SWI", "-", "Prolog", "is", "installed", "in", "Windows", ".", "It", "always", "returns", "None", "as", "the", "path", "of", "the", "resource", "file", "because", "in", "Windows", ...
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L159-L232
train
230,730
yuce/pyswip
pyswip/core.py
_findSwiplLin
def _findSwiplLin(): """ This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) """ # Maybe the exec is on path? (path, swiHome) = _findSwiplFromExec() if path is not None: return (path, swiHome) # If it is not, use find_library path = _findSwiplPathFromFindLib() if path is not None: return (path, swiHome) # Our last try: some hardcoded paths. paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib'] names = ['libswipl.so', 'libpl.so'] path = None for name in names: for try_ in paths: try_ = os.path.join(try_, name) if os.path.exists(try_): path = try_ break if path is not None: return (path, swiHome) return (None, None)
python
def _findSwiplLin(): """ This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) """ # Maybe the exec is on path? (path, swiHome) = _findSwiplFromExec() if path is not None: return (path, swiHome) # If it is not, use find_library path = _findSwiplPathFromFindLib() if path is not None: return (path, swiHome) # Our last try: some hardcoded paths. paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib'] names = ['libswipl.so', 'libpl.so'] path = None for name in names: for try_ in paths: try_ = os.path.join(try_, name) if os.path.exists(try_): path = try_ break if path is not None: return (path, swiHome) return (None, None)
[ "def", "_findSwiplLin", "(", ")", ":", "# Maybe the exec is on path?", "(", "path", ",", "swiHome", ")", "=", "_findSwiplFromExec", "(", ")", "if", "path", "is", "not", "None", ":", "return", "(", "path", ",", "swiHome", ")", "# If it is not, use find_library",...
This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None})
[ "This", "function", "uses", "several", "heuristics", "to", "guess", "where", "SWI", "-", "Prolog", "is", "installed", "in", "Linuxes", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L234-L271
train
230,731
yuce/pyswip
pyswip/core.py
_findSwiplDar
def _findSwiplDar(): """ This function uses several heuristics to guess where SWI-Prolog is installed in MacOS. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) """ # If the exec is in path (path, swiHome) = _findSwiplFromExec() if path is not None: return (path, swiHome) # If it is not, use find_library path = _findSwiplPathFromFindLib() if path is not None: return (path, swiHome) # Last guess, searching for the file paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib'] names = ['libswipl.dylib', 'libpl.dylib'] for name in names: for path in paths: path = os.path.join(path, name) if os.path.exists(path): return (path, None) return (None, None)
python
def _findSwiplDar(): """ This function uses several heuristics to guess where SWI-Prolog is installed in MacOS. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) """ # If the exec is in path (path, swiHome) = _findSwiplFromExec() if path is not None: return (path, swiHome) # If it is not, use find_library path = _findSwiplPathFromFindLib() if path is not None: return (path, swiHome) # Last guess, searching for the file paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib'] names = ['libswipl.dylib', 'libpl.dylib'] for name in names: for path in paths: path = os.path.join(path, name) if os.path.exists(path): return (path, None) return (None, None)
[ "def", "_findSwiplDar", "(", ")", ":", "# If the exec is in path", "(", "path", ",", "swiHome", ")", "=", "_findSwiplFromExec", "(", ")", "if", "path", "is", "not", "None", ":", "return", "(", "path", ",", "swiHome", ")", "# If it is not, use find_library", "...
This function uses several heuristics to guess where SWI-Prolog is installed in MacOS. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None})
[ "This", "function", "uses", "several", "heuristics", "to", "guess", "where", "SWI", "-", "Prolog", "is", "installed", "in", "MacOS", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L358-L390
train
230,732
yuce/pyswip
pyswip/core.py
_fixWindowsPath
def _fixWindowsPath(dll): """ When the path to the DLL is not in Windows search path, Windows will not be able to find other DLLs on the same directory, so we have to add it to the path. This function takes care of it. :parameters: - `dll` (str) - File name of the DLL """ if sys.platform[:3] != 'win': return # Nothing to do here pathToDll = os.path.dirname(dll) currentWindowsPath = os.getenv('PATH') if pathToDll not in currentWindowsPath: # We will prepend the path, to avoid conflicts between DLLs newPath = pathToDll + ';' + currentWindowsPath os.putenv('PATH', newPath)
python
def _fixWindowsPath(dll): """ When the path to the DLL is not in Windows search path, Windows will not be able to find other DLLs on the same directory, so we have to add it to the path. This function takes care of it. :parameters: - `dll` (str) - File name of the DLL """ if sys.platform[:3] != 'win': return # Nothing to do here pathToDll = os.path.dirname(dll) currentWindowsPath = os.getenv('PATH') if pathToDll not in currentWindowsPath: # We will prepend the path, to avoid conflicts between DLLs newPath = pathToDll + ';' + currentWindowsPath os.putenv('PATH', newPath)
[ "def", "_fixWindowsPath", "(", "dll", ")", ":", "if", "sys", ".", "platform", "[", ":", "3", "]", "!=", "'win'", ":", "return", "# Nothing to do here", "pathToDll", "=", "os", ".", "path", ".", "dirname", "(", "dll", ")", "currentWindowsPath", "=", "os",...
When the path to the DLL is not in Windows search path, Windows will not be able to find other DLLs on the same directory, so we have to add it to the path. This function takes care of it. :parameters: - `dll` (str) - File name of the DLL
[ "When", "the", "path", "to", "the", "DLL", "is", "not", "in", "Windows", "search", "path", "Windows", "will", "not", "be", "able", "to", "find", "other", "DLLs", "on", "the", "same", "directory", "so", "we", "have", "to", "add", "it", "to", "the", "p...
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L435-L454
train
230,733
yuce/pyswip
pyswip/core.py
list_to_bytes_list
def list_to_bytes_list(strList): """ This function turns an array of strings into a pointer array with pointers pointing to the encodings of those strings Possibly contained bytes are kept as they are. :param strList: List of strings that shall be converted :type strList: List of strings :returns: Pointer array with pointers pointing to bytes :raises: TypeError if strList is not list, set or tuple """ pList = c_char_p * len(strList) # if strList is already a pointerarray or None, there is nothing to do if isinstance(strList, (pList, type(None))): return strList if not isinstance(strList, (list, set, tuple)): raise TypeError("strList must be list, set or tuple, not " + str(type(strList))) pList = pList() for i, elem in enumerate(strList): pList[i] = str_to_bytes(elem) return pList
python
def list_to_bytes_list(strList): """ This function turns an array of strings into a pointer array with pointers pointing to the encodings of those strings Possibly contained bytes are kept as they are. :param strList: List of strings that shall be converted :type strList: List of strings :returns: Pointer array with pointers pointing to bytes :raises: TypeError if strList is not list, set or tuple """ pList = c_char_p * len(strList) # if strList is already a pointerarray or None, there is nothing to do if isinstance(strList, (pList, type(None))): return strList if not isinstance(strList, (list, set, tuple)): raise TypeError("strList must be list, set or tuple, not " + str(type(strList))) pList = pList() for i, elem in enumerate(strList): pList[i] = str_to_bytes(elem) return pList
[ "def", "list_to_bytes_list", "(", "strList", ")", ":", "pList", "=", "c_char_p", "*", "len", "(", "strList", ")", "# if strList is already a pointerarray or None, there is nothing to do", "if", "isinstance", "(", "strList", ",", "(", "pList", ",", "type", "(", "None...
This function turns an array of strings into a pointer array with pointers pointing to the encodings of those strings Possibly contained bytes are kept as they are. :param strList: List of strings that shall be converted :type strList: List of strings :returns: Pointer array with pointers pointing to bytes :raises: TypeError if strList is not list, set or tuple
[ "This", "function", "turns", "an", "array", "of", "strings", "into", "a", "pointer", "array", "with", "pointers", "pointing", "to", "the", "encodings", "of", "those", "strings", "Possibly", "contained", "bytes", "are", "kept", "as", "they", "are", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L478-L502
train
230,734
yuce/pyswip
pyswip/core.py
check_strings
def check_strings(strings, arrays): """ Decorator function which can be used to automatically turn an incoming string into a bytes object and an incoming list to a pointer array if necessary. :param strings: Indices of the arguments must be pointers to bytes :type strings: List of integers :param arrays: Indices of the arguments must be arrays of pointers to bytes :type arrays: List of integers """ # if given a single element, turn it into a list if isinstance(strings, int): strings = [strings] elif strings is None: strings = [] # check if all entries are integers for i,k in enumerate(strings): if not isinstance(k, int): raise TypeError(('Wrong type for index at {0} '+ 'in strings. Must be int, not {1}!').format(i,k)) # if given a single element, turn it into a list if isinstance(arrays, int): arrays = [arrays] elif arrays is None: arrays = [] # check if all entries are integers for i,k in enumerate(arrays): if not isinstance(k, int): raise TypeError(('Wrong type for index at {0} '+ 'in arrays. Must be int, not {1}!').format(i,k)) # check if some index occurs in both if set(strings).intersection(arrays): raise ValueError('One or more elements occur in both arrays and ' + ' strings. One parameter cannot be both list and string!') # create the checker that will check all arguments given by argsToCheck # and turn them into the right datatype. def checker(func): def check_and_call(*args): args = list(args) for i in strings: arg = args[i] args[i] = str_to_bytes(arg) for i in arrays: arg = args[i] args[i] = list_to_bytes_list(arg) return func(*args) return check_and_call return checker
python
def check_strings(strings, arrays): """ Decorator function which can be used to automatically turn an incoming string into a bytes object and an incoming list to a pointer array if necessary. :param strings: Indices of the arguments must be pointers to bytes :type strings: List of integers :param arrays: Indices of the arguments must be arrays of pointers to bytes :type arrays: List of integers """ # if given a single element, turn it into a list if isinstance(strings, int): strings = [strings] elif strings is None: strings = [] # check if all entries are integers for i,k in enumerate(strings): if not isinstance(k, int): raise TypeError(('Wrong type for index at {0} '+ 'in strings. Must be int, not {1}!').format(i,k)) # if given a single element, turn it into a list if isinstance(arrays, int): arrays = [arrays] elif arrays is None: arrays = [] # check if all entries are integers for i,k in enumerate(arrays): if not isinstance(k, int): raise TypeError(('Wrong type for index at {0} '+ 'in arrays. Must be int, not {1}!').format(i,k)) # check if some index occurs in both if set(strings).intersection(arrays): raise ValueError('One or more elements occur in both arrays and ' + ' strings. One parameter cannot be both list and string!') # create the checker that will check all arguments given by argsToCheck # and turn them into the right datatype. def checker(func): def check_and_call(*args): args = list(args) for i in strings: arg = args[i] args[i] = str_to_bytes(arg) for i in arrays: arg = args[i] args[i] = list_to_bytes_list(arg) return func(*args) return check_and_call return checker
[ "def", "check_strings", "(", "strings", ",", "arrays", ")", ":", "# if given a single element, turn it into a list", "if", "isinstance", "(", "strings", ",", "int", ")", ":", "strings", "=", "[", "strings", "]", "elif", "strings", "is", "None", ":", "strings", ...
Decorator function which can be used to automatically turn an incoming string into a bytes object and an incoming list to a pointer array if necessary. :param strings: Indices of the arguments must be pointers to bytes :type strings: List of integers :param arrays: Indices of the arguments must be arrays of pointers to bytes :type arrays: List of integers
[ "Decorator", "function", "which", "can", "be", "used", "to", "automatically", "turn", "an", "incoming", "string", "into", "a", "bytes", "object", "and", "an", "incoming", "list", "to", "a", "pointer", "array", "if", "necessary", "." ]
f7c1f1e8c3a13b90bd775861d374788a8b5677d8
https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L506-L563
train
230,735
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.add
def add(self, item): """ Adds the specified item to this queue if there is available space. :param item: (object), the specified item. :return: (bool), ``true`` if element is successfully added, ``false`` otherwise. """ def result_fnc(f): if f.result(): return True raise Full("Queue is full!") return self.offer(item).continue_with(result_fnc)
python
def add(self, item): """ Adds the specified item to this queue if there is available space. :param item: (object), the specified item. :return: (bool), ``true`` if element is successfully added, ``false`` otherwise. """ def result_fnc(f): if f.result(): return True raise Full("Queue is full!") return self.offer(item).continue_with(result_fnc)
[ "def", "add", "(", "self", ",", "item", ")", ":", "def", "result_fnc", "(", "f", ")", ":", "if", "f", ".", "result", "(", ")", ":", "return", "True", "raise", "Full", "(", "\"Queue is full!\"", ")", "return", "self", ".", "offer", "(", "item", ")",...
Adds the specified item to this queue if there is available space. :param item: (object), the specified item. :return: (bool), ``true`` if element is successfully added, ``false`` otherwise.
[ "Adds", "the", "specified", "item", "to", "this", "queue", "if", "there", "is", "available", "space", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L39-L51
train
230,736
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.add_all
def add_all(self, items): """ Adds the elements in the specified collection to this queue. :param items: (Collection), collection which includes the items to be added. :return: (bool), ``true`` if this queue is changed after call, ``false`` otherwise. """ check_not_none(items, "Value can't be None") data_items = [] for item in items: check_not_none(item, "Value can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_add_all_codec, data_list=data_items)
python
def add_all(self, items): """ Adds the elements in the specified collection to this queue. :param items: (Collection), collection which includes the items to be added. :return: (bool), ``true`` if this queue is changed after call, ``false`` otherwise. """ check_not_none(items, "Value can't be None") data_items = [] for item in items: check_not_none(item, "Value can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_add_all_codec, data_list=data_items)
[ "def", "add_all", "(", "self", ",", "items", ")", ":", "check_not_none", "(", "items", ",", "\"Value can't be None\"", ")", "data_items", "=", "[", "]", "for", "item", "in", "items", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", "d...
Adds the elements in the specified collection to this queue. :param items: (Collection), collection which includes the items to be added. :return: (bool), ``true`` if this queue is changed after call, ``false`` otherwise.
[ "Adds", "the", "elements", "in", "the", "specified", "collection", "to", "this", "queue", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L53-L65
train
230,737
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.contains_all
def contains_all(self, items): """ Determines whether this queue contains all of the items in the specified collection or not. :param items: (Collection), the specified collection which includes the items to be searched. :return: (bool), ``true`` if all of the items in the specified collection exist in this queue, ``false`` otherwise. """ check_not_none(items, "Items can't be None") data_items = [] for item in items: check_not_none(item, "item can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_contains_all_codec, data_list=data_items)
python
def contains_all(self, items): """ Determines whether this queue contains all of the items in the specified collection or not. :param items: (Collection), the specified collection which includes the items to be searched. :return: (bool), ``true`` if all of the items in the specified collection exist in this queue, ``false`` otherwise. """ check_not_none(items, "Items can't be None") data_items = [] for item in items: check_not_none(item, "item can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_contains_all_codec, data_list=data_items)
[ "def", "contains_all", "(", "self", ",", "items", ")", ":", "check_not_none", "(", "items", ",", "\"Items can't be None\"", ")", "data_items", "=", "[", "]", "for", "item", "in", "items", ":", "check_not_none", "(", "item", ",", "\"item can't be None\"", ")", ...
Determines whether this queue contains all of the items in the specified collection or not. :param items: (Collection), the specified collection which includes the items to be searched. :return: (bool), ``true`` if all of the items in the specified collection exist in this queue, ``false`` otherwise.
[ "Determines", "whether", "this", "queue", "contains", "all", "of", "the", "items", "in", "the", "specified", "collection", "or", "not", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L112-L124
train
230,738
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.drain_to
def drain_to(self, list, max_size=-1): """ Transfers all available items to the given `list`_ and removes these items from this queue. If a max_size is specified, it transfers at most the given number of items. In case of a failure, an item can exist in both collections or none of them. This operation may be more efficient than polling elements repeatedly and putting into collection. :param list: (`list`_), the list where the items in this queue will be transferred. :param max_size: (int), the maximum number items to transfer (optional). :return: (int), number of transferred items. .. _list: https://docs.python.org/2/library/functions.html#list """ def drain_result(f): resp = f.result() list.extend(resp) return len(resp) return self._encode_invoke(queue_drain_to_max_size_codec, max_size=max_size).continue_with( drain_result)
python
def drain_to(self, list, max_size=-1): """ Transfers all available items to the given `list`_ and removes these items from this queue. If a max_size is specified, it transfers at most the given number of items. In case of a failure, an item can exist in both collections or none of them. This operation may be more efficient than polling elements repeatedly and putting into collection. :param list: (`list`_), the list where the items in this queue will be transferred. :param max_size: (int), the maximum number items to transfer (optional). :return: (int), number of transferred items. .. _list: https://docs.python.org/2/library/functions.html#list """ def drain_result(f): resp = f.result() list.extend(resp) return len(resp) return self._encode_invoke(queue_drain_to_max_size_codec, max_size=max_size).continue_with( drain_result)
[ "def", "drain_to", "(", "self", ",", "list", ",", "max_size", "=", "-", "1", ")", ":", "def", "drain_result", "(", "f", ")", ":", "resp", "=", "f", ".", "result", "(", ")", "list", ".", "extend", "(", "resp", ")", "return", "len", "(", "resp", ...
Transfers all available items to the given `list`_ and removes these items from this queue. If a max_size is specified, it transfers at most the given number of items. In case of a failure, an item can exist in both collections or none of them. This operation may be more efficient than polling elements repeatedly and putting into collection. :param list: (`list`_), the list where the items in this queue will be transferred. :param max_size: (int), the maximum number items to transfer (optional). :return: (int), number of transferred items. .. _list: https://docs.python.org/2/library/functions.html#list
[ "Transfers", "all", "available", "items", "to", "the", "given", "list", "_", "and", "removes", "these", "items", "from", "this", "queue", ".", "If", "a", "max_size", "is", "specified", "it", "transfers", "at", "most", "the", "given", "number", "of", "items...
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L126-L146
train
230,739
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.put
def put(self, item): """ Adds the specified element into this queue. If there is no space, it waits until necessary space becomes available. :param item: (object), the specified item. """ check_not_none(item, "Value can't be None") element_data = self._to_data(item) return self._encode_invoke(queue_put_codec, value=element_data)
python
def put(self, item): """ Adds the specified element into this queue. If there is no space, it waits until necessary space becomes available. :param item: (object), the specified item. """ check_not_none(item, "Value can't be None") element_data = self._to_data(item) return self._encode_invoke(queue_put_codec, value=element_data)
[ "def", "put", "(", "self", ",", "item", ")", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", "element_data", "=", "self", ".", "_to_data", "(", "item", ")", "return", "self", ".", "_encode_invoke", "(", "queue_put_codec", ",", "value...
Adds the specified element into this queue. If there is no space, it waits until necessary space becomes available. :param item: (object), the specified item.
[ "Adds", "the", "specified", "element", "into", "this", "queue", ".", "If", "there", "is", "no", "space", "it", "waits", "until", "necessary", "space", "becomes", "available", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L199-L208
train
230,740
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.remove_all
def remove_all(self, items): """ Removes all of the elements of the specified collection from this queue. :param items: (Collection), the specified collection. :return: (bool), ``true`` if the call changed this queue, ``false`` otherwise. """ check_not_none(items, "Value can't be None") data_items = [] for item in items: check_not_none(item, "Value can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_compare_and_remove_all_codec, data_list=data_items)
python
def remove_all(self, items): """ Removes all of the elements of the specified collection from this queue. :param items: (Collection), the specified collection. :return: (bool), ``true`` if the call changed this queue, ``false`` otherwise. """ check_not_none(items, "Value can't be None") data_items = [] for item in items: check_not_none(item, "Value can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_compare_and_remove_all_codec, data_list=data_items)
[ "def", "remove_all", "(", "self", ",", "items", ")", ":", "check_not_none", "(", "items", ",", "\"Value can't be None\"", ")", "data_items", "=", "[", "]", "for", "item", "in", "items", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", ...
Removes all of the elements of the specified collection from this queue. :param items: (Collection), the specified collection. :return: (bool), ``true`` if the call changed this queue, ``false`` otherwise.
[ "Removes", "all", "of", "the", "elements", "of", "the", "specified", "collection", "from", "this", "queue", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L229-L241
train
230,741
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
Queue.retain_all
def retain_all(self, items): """ Removes the items which are not contained in the specified collection. In other words, only the items that are contained in the specified collection will be retained. :param items: (Collection), collection which includes the elements to be retained in this set. :return: (bool), ``true`` if this queue changed as a result of the call. """ check_not_none(items, "Value can't be None") data_items = [] for item in items: check_not_none(item, "Value can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_compare_and_retain_all_codec, data_list=data_items)
python
def retain_all(self, items): """ Removes the items which are not contained in the specified collection. In other words, only the items that are contained in the specified collection will be retained. :param items: (Collection), collection which includes the elements to be retained in this set. :return: (bool), ``true`` if this queue changed as a result of the call. """ check_not_none(items, "Value can't be None") data_items = [] for item in items: check_not_none(item, "Value can't be None") data_items.append(self._to_data(item)) return self._encode_invoke(queue_compare_and_retain_all_codec, data_list=data_items)
[ "def", "retain_all", "(", "self", ",", "items", ")", ":", "check_not_none", "(", "items", ",", "\"Value can't be None\"", ")", "data_items", "=", "[", "]", "for", "item", "in", "items", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", ...
Removes the items which are not contained in the specified collection. In other words, only the items that are contained in the specified collection will be retained. :param items: (Collection), collection which includes the elements to be retained in this set. :return: (bool), ``true`` if this queue changed as a result of the call.
[ "Removes", "the", "items", "which", "are", "not", "contained", "in", "the", "specified", "collection", ".", "In", "other", "words", "only", "the", "items", "that", "are", "contained", "in", "the", "specified", "collection", "will", "be", "retained", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L252-L265
train
230,742
hazelcast/hazelcast-python-client
hazelcast/proxy/pn_counter.py
PNCounter.get_and_add
def get_and_add(self, delta): """ Adds the given value to the current value and returns the previous value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to add. :return: (int), the previous value. """ return self._invoke_internal(pn_counter_add_codec, delta=delta, get_before_update=True)
python
def get_and_add(self, delta): """ Adds the given value to the current value and returns the previous value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to add. :return: (int), the previous value. """ return self._invoke_internal(pn_counter_add_codec, delta=delta, get_before_update=True)
[ "def", "get_and_add", "(", "self", ",", "delta", ")", ":", "return", "self", ".", "_invoke_internal", "(", "pn_counter_add_codec", ",", "delta", "=", "delta", ",", "get_before_update", "=", "True", ")" ]
Adds the given value to the current value and returns the previous value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to add. :return: (int), the previous value.
[ "Adds", "the", "given", "value", "to", "the", "current", "value", "and", "returns", "the", "previous", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/pn_counter.py#L77-L89
train
230,743
hazelcast/hazelcast-python-client
hazelcast/proxy/pn_counter.py
PNCounter.add_and_get
def add_and_get(self, delta): """ Adds the given value to the current value and returns the updated value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to add. :return: (int), the updated value. """ return self._invoke_internal(pn_counter_add_codec, delta=delta, get_before_update=False)
python
def add_and_get(self, delta): """ Adds the given value to the current value and returns the updated value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to add. :return: (int), the updated value. """ return self._invoke_internal(pn_counter_add_codec, delta=delta, get_before_update=False)
[ "def", "add_and_get", "(", "self", ",", "delta", ")", ":", "return", "self", ".", "_invoke_internal", "(", "pn_counter_add_codec", ",", "delta", "=", "delta", ",", "get_before_update", "=", "False", ")" ]
Adds the given value to the current value and returns the updated value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to add. :return: (int), the updated value.
[ "Adds", "the", "given", "value", "to", "the", "current", "value", "and", "returns", "the", "updated", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/pn_counter.py#L91-L103
train
230,744
hazelcast/hazelcast-python-client
hazelcast/proxy/pn_counter.py
PNCounter.get_and_subtract
def get_and_subtract(self, delta): """ Subtracts the given value from the current value and returns the previous value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to subtract. :return: (int), the previous value. """ return self._invoke_internal(pn_counter_add_codec, delta=-1 * delta, get_before_update=True)
python
def get_and_subtract(self, delta): """ Subtracts the given value from the current value and returns the previous value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to subtract. :return: (int), the previous value. """ return self._invoke_internal(pn_counter_add_codec, delta=-1 * delta, get_before_update=True)
[ "def", "get_and_subtract", "(", "self", ",", "delta", ")", ":", "return", "self", ".", "_invoke_internal", "(", "pn_counter_add_codec", ",", "delta", "=", "-", "1", "*", "delta", ",", "get_before_update", "=", "True", ")" ]
Subtracts the given value from the current value and returns the previous value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to subtract. :return: (int), the previous value.
[ "Subtracts", "the", "given", "value", "from", "the", "current", "value", "and", "returns", "the", "previous", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/pn_counter.py#L105-L117
train
230,745
hazelcast/hazelcast-python-client
hazelcast/proxy/pn_counter.py
PNCounter.subtract_and_get
def subtract_and_get(self, delta): """ Subtracts the given value from the current value and returns the updated value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to subtract. :return: (int), the updated value. """ return self._invoke_internal(pn_counter_add_codec, delta=-1 * delta, get_before_update=False)
python
def subtract_and_get(self, delta): """ Subtracts the given value from the current value and returns the updated value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to subtract. :return: (int), the updated value. """ return self._invoke_internal(pn_counter_add_codec, delta=-1 * delta, get_before_update=False)
[ "def", "subtract_and_get", "(", "self", ",", "delta", ")", ":", "return", "self", ".", "_invoke_internal", "(", "pn_counter_add_codec", ",", "delta", "=", "-", "1", "*", "delta", ",", "get_before_update", "=", "False", ")" ]
Subtracts the given value from the current value and returns the updated value. :raises NoDataMemberInClusterError: if the cluster does not contain any data members. :raises UnsupportedOperationError: if the cluster version is less than 3.10. :raises ConsistencyLostError: if the session guarantees have been lost. :param delta: (int), the value to subtract. :return: (int), the updated value.
[ "Subtracts", "the", "given", "value", "from", "the", "current", "value", "and", "returns", "the", "updated", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/pn_counter.py#L119-L131
train
230,746
hazelcast/hazelcast-python-client
hazelcast/client.py
HazelcastClient.shutdown
def shutdown(self): """ Shuts down this HazelcastClient. """ if self.lifecycle.is_live: self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTTING_DOWN) self.near_cache_manager.destroy_all_near_caches() self.statistics.shutdown() self.partition_service.shutdown() self.heartbeat.shutdown() self.cluster.shutdown() self.reactor.shutdown() self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTDOWN) self.logger.info("Client shutdown.", extra=self._logger_extras)
python
def shutdown(self): """ Shuts down this HazelcastClient. """ if self.lifecycle.is_live: self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTTING_DOWN) self.near_cache_manager.destroy_all_near_caches() self.statistics.shutdown() self.partition_service.shutdown() self.heartbeat.shutdown() self.cluster.shutdown() self.reactor.shutdown() self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTDOWN) self.logger.info("Client shutdown.", extra=self._logger_extras)
[ "def", "shutdown", "(", "self", ")", ":", "if", "self", ".", "lifecycle", ".", "is_live", ":", "self", ".", "lifecycle", ".", "fire_lifecycle_event", "(", "LIFECYCLE_STATE_SHUTTING_DOWN", ")", "self", ".", "near_cache_manager", ".", "destroy_all_near_caches", "(",...
Shuts down this HazelcastClient.
[ "Shuts", "down", "this", "HazelcastClient", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/client.py#L251-L264
train
230,747
hazelcast/hazelcast-python-client
hazelcast/proxy/topic.py
Topic.publish
def publish(self, message): """ Publishes the message to all subscribers of this topic :param message: (object), the message to be published. """ message_data = self._to_data(message) self._encode_invoke(topic_publish_codec, message=message_data)
python
def publish(self, message): """ Publishes the message to all subscribers of this topic :param message: (object), the message to be published. """ message_data = self._to_data(message) self._encode_invoke(topic_publish_codec, message=message_data)
[ "def", "publish", "(", "self", ",", "message", ")", ":", "message_data", "=", "self", ".", "_to_data", "(", "message", ")", "self", ".", "_encode_invoke", "(", "topic_publish_codec", ",", "message", "=", "message_data", ")" ]
Publishes the message to all subscribers of this topic :param message: (object), the message to be published.
[ "Publishes", "the", "message", "to", "all", "subscribers", "of", "this", "topic" ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/topic.py#L39-L46
train
230,748
hazelcast/hazelcast-python-client
hazelcast/proxy/topic.py
Topic.remove_listener
def remove_listener(self, registration_id): """ Stops receiving messages for the given message listener. If the given listener already removed, this method does nothing. :param registration_id: (str), registration id of the listener to be removed. :return: (bool), ``true`` if the listener is removed, ``false`` otherwise. """ return self._stop_listening(registration_id, lambda i: topic_remove_message_listener_codec.encode_request(self.name, i))
python
def remove_listener(self, registration_id): """ Stops receiving messages for the given message listener. If the given listener already removed, this method does nothing. :param registration_id: (str), registration id of the listener to be removed. :return: (bool), ``true`` if the listener is removed, ``false`` otherwise. """ return self._stop_listening(registration_id, lambda i: topic_remove_message_listener_codec.encode_request(self.name, i))
[ "def", "remove_listener", "(", "self", ",", "registration_id", ")", ":", "return", "self", ".", "_stop_listening", "(", "registration_id", ",", "lambda", "i", ":", "topic_remove_message_listener_codec", ".", "encode_request", "(", "self", ".", "name", ",", "i", ...
Stops receiving messages for the given message listener. If the given listener already removed, this method does nothing. :param registration_id: (str), registration id of the listener to be removed. :return: (bool), ``true`` if the listener is removed, ``false`` otherwise.
[ "Stops", "receiving", "messages", "for", "the", "given", "message", "listener", ".", "If", "the", "given", "listener", "already", "removed", "this", "method", "does", "nothing", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/topic.py#L48-L57
train
230,749
hazelcast/hazelcast-python-client
hazelcast/util.py
validate_serializer
def validate_serializer(serializer, _type): """ Validates the serializer for given type. :param serializer: (Serializer), the serializer to be validated. :param _type: (Type), type to be used for serializer validation. """ if not issubclass(serializer, _type): raise ValueError("Serializer should be an instance of {}".format(_type.__name__))
python
def validate_serializer(serializer, _type): """ Validates the serializer for given type. :param serializer: (Serializer), the serializer to be validated. :param _type: (Type), type to be used for serializer validation. """ if not issubclass(serializer, _type): raise ValueError("Serializer should be an instance of {}".format(_type.__name__))
[ "def", "validate_serializer", "(", "serializer", ",", "_type", ")", ":", "if", "not", "issubclass", "(", "serializer", ",", "_type", ")", ":", "raise", "ValueError", "(", "\"Serializer should be an instance of {}\"", ".", "format", "(", "_type", ".", "__name__", ...
Validates the serializer for given type. :param serializer: (Serializer), the serializer to be validated. :param _type: (Type), type to be used for serializer validation.
[ "Validates", "the", "serializer", "for", "given", "type", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/util.py#L119-L127
train
230,750
hazelcast/hazelcast-python-client
hazelcast/exception.py
create_exception
def create_exception(error_codec): """ Creates an exception with given error codec. :param error_codec: (Error Codec), error codec which includes the class name, message and exception trace. :return: (Exception), the created exception. """ if error_codec.error_code in ERROR_CODE_TO_ERROR: return ERROR_CODE_TO_ERROR[error_codec.error_code](error_codec.message) stack_trace = "\n".join( ["\tat %s.%s(%s:%s)" % (x.declaring_class, x.method_name, x.file_name, x.line_number) for x in error_codec.stack_trace]) message = "Got exception from server:\n %s: %s\n %s" % (error_codec.class_name, error_codec.message, stack_trace) return HazelcastError(message)
python
def create_exception(error_codec): """ Creates an exception with given error codec. :param error_codec: (Error Codec), error codec which includes the class name, message and exception trace. :return: (Exception), the created exception. """ if error_codec.error_code in ERROR_CODE_TO_ERROR: return ERROR_CODE_TO_ERROR[error_codec.error_code](error_codec.message) stack_trace = "\n".join( ["\tat %s.%s(%s:%s)" % (x.declaring_class, x.method_name, x.file_name, x.line_number) for x in error_codec.stack_trace]) message = "Got exception from server:\n %s: %s\n %s" % (error_codec.class_name, error_codec.message, stack_trace) return HazelcastError(message)
[ "def", "create_exception", "(", "error_codec", ")", ":", "if", "error_codec", ".", "error_code", "in", "ERROR_CODE_TO_ERROR", ":", "return", "ERROR_CODE_TO_ERROR", "[", "error_codec", ".", "error_code", "]", "(", "error_codec", ".", "message", ")", "stack_trace", ...
Creates an exception with given error codec. :param error_codec: (Error Codec), error codec which includes the class name, message and exception trace. :return: (Exception), the created exception.
[ "Creates", "an", "exception", "with", "given", "error", "codec", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/exception.py#L460-L476
train
230,751
hazelcast/hazelcast-python-client
hazelcast/proxy/ringbuffer.py
Ringbuffer.capacity
def capacity(self): """ Returns the capacity of this Ringbuffer. :return: (long), the capacity of Ringbuffer. """ if not self._capacity: def cache_capacity(f): self._capacity = f.result() return f.result() return self._encode_invoke(ringbuffer_capacity_codec).continue_with(cache_capacity) return ImmediateFuture(self._capacity)
python
def capacity(self): """ Returns the capacity of this Ringbuffer. :return: (long), the capacity of Ringbuffer. """ if not self._capacity: def cache_capacity(f): self._capacity = f.result() return f.result() return self._encode_invoke(ringbuffer_capacity_codec).continue_with(cache_capacity) return ImmediateFuture(self._capacity)
[ "def", "capacity", "(", "self", ")", ":", "if", "not", "self", ".", "_capacity", ":", "def", "cache_capacity", "(", "f", ")", ":", "self", ".", "_capacity", "=", "f", ".", "result", "(", ")", "return", "f", ".", "result", "(", ")", "return", "self"...
Returns the capacity of this Ringbuffer. :return: (long), the capacity of Ringbuffer.
[ "Returns", "the", "capacity", "of", "this", "Ringbuffer", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/ringbuffer.py#L53-L65
train
230,752
hazelcast/hazelcast-python-client
hazelcast/proxy/ringbuffer.py
Ringbuffer.read_one
def read_one(self, sequence): """ Reads one item from the Ringbuffer. If the sequence is one beyond the current tail, this call blocks until an item is added. Currently it isn't possible to control how long this call is going to block. :param sequence: (long), the sequence of the item to read. :return: (object), the read item. """ check_not_negative(sequence, "sequence can't be smaller than 0") return self._encode_invoke(ringbuffer_read_one_codec, sequence=sequence)
python
def read_one(self, sequence): """ Reads one item from the Ringbuffer. If the sequence is one beyond the current tail, this call blocks until an item is added. Currently it isn't possible to control how long this call is going to block. :param sequence: (long), the sequence of the item to read. :return: (object), the read item. """ check_not_negative(sequence, "sequence can't be smaller than 0") return self._encode_invoke(ringbuffer_read_one_codec, sequence=sequence)
[ "def", "read_one", "(", "self", ",", "sequence", ")", ":", "check_not_negative", "(", "sequence", ",", "\"sequence can't be smaller than 0\"", ")", "return", "self", ".", "_encode_invoke", "(", "ringbuffer_read_one_codec", ",", "sequence", "=", "sequence", ")" ]
Reads one item from the Ringbuffer. If the sequence is one beyond the current tail, this call blocks until an item is added. Currently it isn't possible to control how long this call is going to block. :param sequence: (long), the sequence of the item to read. :return: (object), the read item.
[ "Reads", "one", "item", "from", "the", "Ringbuffer", ".", "If", "the", "sequence", "is", "one", "beyond", "the", "current", "tail", "this", "call", "blocks", "until", "an", "item", "is", "added", ".", "Currently", "it", "isn", "t", "possible", "to", "con...
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/ringbuffer.py#L135-L144
train
230,753
hazelcast/hazelcast-python-client
hazelcast/proxy/ringbuffer.py
Ringbuffer.read_many
def read_many(self, start_sequence, min_count, max_count): """ Reads a batch of items from the Ringbuffer. If the number of available items after the first read item is smaller than the max_count, these items are returned. So it could be the number of items read is smaller than the max_count. If there are less items available than min_count, then this call blocks. Reading a batch of items is likely to perform better because less overhead is involved. :param start_sequence: (long), the start_sequence of the first item to read. :param min_count: (int), the minimum number of items to read. :param max_count: (int), the maximum number of items to read. :return: (Sequence), the list of read items. """ check_not_negative(start_sequence, "sequence can't be smaller than 0") check_true(max_count >= min_count, "max count should be greater or equal to min count") check_true(min_count <= self.capacity().result(), "min count should be smaller or equal to capacity") check_true(max_count < MAX_BATCH_SIZE, "max count can't be greater than %d" % MAX_BATCH_SIZE) return self._encode_invoke(ringbuffer_read_many_codec, response_handler=self._read_many_response_handler, start_sequence=start_sequence, min_count=min_count, max_count=max_count, filter=None)
python
def read_many(self, start_sequence, min_count, max_count): """ Reads a batch of items from the Ringbuffer. If the number of available items after the first read item is smaller than the max_count, these items are returned. So it could be the number of items read is smaller than the max_count. If there are less items available than min_count, then this call blocks. Reading a batch of items is likely to perform better because less overhead is involved. :param start_sequence: (long), the start_sequence of the first item to read. :param min_count: (int), the minimum number of items to read. :param max_count: (int), the maximum number of items to read. :return: (Sequence), the list of read items. """ check_not_negative(start_sequence, "sequence can't be smaller than 0") check_true(max_count >= min_count, "max count should be greater or equal to min count") check_true(min_count <= self.capacity().result(), "min count should be smaller or equal to capacity") check_true(max_count < MAX_BATCH_SIZE, "max count can't be greater than %d" % MAX_BATCH_SIZE) return self._encode_invoke(ringbuffer_read_many_codec, response_handler=self._read_many_response_handler, start_sequence=start_sequence, min_count=min_count, max_count=max_count, filter=None)
[ "def", "read_many", "(", "self", ",", "start_sequence", ",", "min_count", ",", "max_count", ")", ":", "check_not_negative", "(", "start_sequence", ",", "\"sequence can't be smaller than 0\"", ")", "check_true", "(", "max_count", ">=", "min_count", ",", "\"max count sh...
Reads a batch of items from the Ringbuffer. If the number of available items after the first read item is smaller than the max_count, these items are returned. So it could be the number of items read is smaller than the max_count. If there are less items available than min_count, then this call blocks. Reading a batch of items is likely to perform better because less overhead is involved. :param start_sequence: (long), the start_sequence of the first item to read. :param min_count: (int), the minimum number of items to read. :param max_count: (int), the maximum number of items to read. :return: (Sequence), the list of read items.
[ "Reads", "a", "batch", "of", "items", "from", "the", "Ringbuffer", ".", "If", "the", "number", "of", "available", "items", "after", "the", "first", "read", "item", "is", "smaller", "than", "the", "max_count", "these", "items", "are", "returned", ".", "So",...
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/ringbuffer.py#L146-L165
train
230,754
hazelcast/hazelcast-python-client
hazelcast/proxy/id_generator.py
IdGenerator.init
def init(self, initial): """ Try to initialize this IdGenerator instance with the given id. The first generated id will be 1 greater than id. :param initial: (long), the given id. :return: (bool), ``true`` if initialization succeeded, ``false`` if id is less than 0. """ if initial <= 0: return False step = initial // BLOCK_SIZE with self._lock: init = self._atomic_long.compare_and_set(0, step + 1).result() if init: self._local = step self._residue = (initial % BLOCK_SIZE) + 1 return init
python
def init(self, initial): """ Try to initialize this IdGenerator instance with the given id. The first generated id will be 1 greater than id. :param initial: (long), the given id. :return: (bool), ``true`` if initialization succeeded, ``false`` if id is less than 0. """ if initial <= 0: return False step = initial // BLOCK_SIZE with self._lock: init = self._atomic_long.compare_and_set(0, step + 1).result() if init: self._local = step self._residue = (initial % BLOCK_SIZE) + 1 return init
[ "def", "init", "(", "self", ",", "initial", ")", ":", "if", "initial", "<=", "0", ":", "return", "False", "step", "=", "initial", "//", "BLOCK_SIZE", "with", "self", ".", "_lock", ":", "init", "=", "self", ".", "_atomic_long", ".", "compare_and_set", "...
Try to initialize this IdGenerator instance with the given id. The first generated id will be 1 greater than id. :param initial: (long), the given id. :return: (bool), ``true`` if initialization succeeded, ``false`` if id is less than 0.
[ "Try", "to", "initialize", "this", "IdGenerator", "instance", "with", "the", "given", "id", ".", "The", "first", "generated", "id", "will", "be", "1", "greater", "than", "id", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/id_generator.py#L31-L46
train
230,755
hazelcast/hazelcast-python-client
hazelcast/proxy/id_generator.py
IdGenerator.new_id
def new_id(self): """ Generates and returns a cluster-wide unique id. Generated ids are guaranteed to be unique for the entire cluster as long as the cluster is live. If the cluster restarts, then id generation will start from 0. :return: (long), cluster-wide new unique id. """ with self._lock: curr = self._residue self._residue += 1 if self._residue >= BLOCK_SIZE: increment = self._atomic_long.get_and_increment().result() self._local = increment self._residue = 0 return self.new_id() return self._local * BLOCK_SIZE + curr
python
def new_id(self): """ Generates and returns a cluster-wide unique id. Generated ids are guaranteed to be unique for the entire cluster as long as the cluster is live. If the cluster restarts, then id generation will start from 0. :return: (long), cluster-wide new unique id. """ with self._lock: curr = self._residue self._residue += 1 if self._residue >= BLOCK_SIZE: increment = self._atomic_long.get_and_increment().result() self._local = increment self._residue = 0 return self.new_id() return self._local * BLOCK_SIZE + curr
[ "def", "new_id", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "curr", "=", "self", ".", "_residue", "self", ".", "_residue", "+=", "1", "if", "self", ".", "_residue", ">=", "BLOCK_SIZE", ":", "increment", "=", "self", ".", "_atomic_long", ...
Generates and returns a cluster-wide unique id. Generated ids are guaranteed to be unique for the entire cluster as long as the cluster is live. If the cluster restarts, then id generation will start from 0. :return: (long), cluster-wide new unique id.
[ "Generates", "and", "returns", "a", "cluster", "-", "wide", "unique", "id", ".", "Generated", "ids", "are", "guaranteed", "to", "be", "unique", "for", "the", "entire", "cluster", "as", "long", "as", "the", "cluster", "is", "live", ".", "If", "the", "clus...
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/id_generator.py#L48-L63
train
230,756
hazelcast/hazelcast-python-client
hazelcast/proxy/executor.py
Executor.execute_on_key_owner
def execute_on_key_owner(self, key, task): """ Executes a task on the owner of the specified key. :param key: (object), the specified key. :param task: (Task), a task executed on the owner of the specified key. :return: (:class:`~hazelcast.future.Future`), future representing pending completion of the task. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) partition_id = self._client.partition_service.get_partition_id(key_data) uuid = self._get_uuid() return self._encode_invoke_on_partition(executor_service_submit_to_partition_codec, partition_id, uuid=uuid, callable=self._to_data(task), partition_id=partition_id)
python
def execute_on_key_owner(self, key, task): """ Executes a task on the owner of the specified key. :param key: (object), the specified key. :param task: (Task), a task executed on the owner of the specified key. :return: (:class:`~hazelcast.future.Future`), future representing pending completion of the task. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) partition_id = self._client.partition_service.get_partition_id(key_data) uuid = self._get_uuid() return self._encode_invoke_on_partition(executor_service_submit_to_partition_codec, partition_id, uuid=uuid, callable=self._to_data(task), partition_id=partition_id)
[ "def", "execute_on_key_owner", "(", "self", ",", "key", ",", "task", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "partition_id", "=", "self", ".", "_client", ".", "pa...
Executes a task on the owner of the specified key. :param key: (object), the specified key. :param task: (Task), a task executed on the owner of the specified key. :return: (:class:`~hazelcast.future.Future`), future representing pending completion of the task.
[ "Executes", "a", "task", "on", "the", "owner", "of", "the", "specified", "key", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/executor.py#L15-L30
train
230,757
hazelcast/hazelcast-python-client
hazelcast/proxy/executor.py
Executor.execute_on_member
def execute_on_member(self, member, task): """ Executes a task on the specified member. :param member: (Member), the specified member. :param task: (Task), the task executed on the specified member. :return: (:class:`~hazelcast.future.Future`), Future representing pending completion of the task. """ uuid = self._get_uuid() address = member.address return self._execute_on_member(address, uuid, self._to_data(task))
python
def execute_on_member(self, member, task): """ Executes a task on the specified member. :param member: (Member), the specified member. :param task: (Task), the task executed on the specified member. :return: (:class:`~hazelcast.future.Future`), Future representing pending completion of the task. """ uuid = self._get_uuid() address = member.address return self._execute_on_member(address, uuid, self._to_data(task))
[ "def", "execute_on_member", "(", "self", ",", "member", ",", "task", ")", ":", "uuid", "=", "self", ".", "_get_uuid", "(", ")", "address", "=", "member", ".", "address", "return", "self", ".", "_execute_on_member", "(", "address", ",", "uuid", ",", "self...
Executes a task on the specified member. :param member: (Member), the specified member. :param task: (Task), the task executed on the specified member. :return: (:class:`~hazelcast.future.Future`), Future representing pending completion of the task.
[ "Executes", "a", "task", "on", "the", "specified", "member", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/executor.py#L32-L42
train
230,758
hazelcast/hazelcast-python-client
hazelcast/proxy/executor.py
Executor.execute_on_members
def execute_on_members(self, members, task): """ Executes a task on each of the specified members. :param members: (Collection), the specified members. :param task: (Task), the task executed on the specified members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member. """ task_data = self._to_data(task) futures = [] uuid = self._get_uuid() for member in members: f = self._execute_on_member(member.address, uuid, task_data) futures.append(f) return future.combine_futures(*futures)
python
def execute_on_members(self, members, task): """ Executes a task on each of the specified members. :param members: (Collection), the specified members. :param task: (Task), the task executed on the specified members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member. """ task_data = self._to_data(task) futures = [] uuid = self._get_uuid() for member in members: f = self._execute_on_member(member.address, uuid, task_data) futures.append(f) return future.combine_futures(*futures)
[ "def", "execute_on_members", "(", "self", ",", "members", ",", "task", ")", ":", "task_data", "=", "self", ".", "_to_data", "(", "task", ")", "futures", "=", "[", "]", "uuid", "=", "self", ".", "_get_uuid", "(", ")", "for", "member", "in", "members", ...
Executes a task on each of the specified members. :param members: (Collection), the specified members. :param task: (Task), the task executed on the specified members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member.
[ "Executes", "a", "task", "on", "each", "of", "the", "specified", "members", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/executor.py#L44-L58
train
230,759
hazelcast/hazelcast-python-client
hazelcast/proxy/executor.py
Executor.execute_on_all_members
def execute_on_all_members(self, task): """ Executes a task on all of the known cluster members. :param task: (Task), the task executed on the all of the members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member. """ return self.execute_on_members(self._client.cluster.get_member_list(), task)
python
def execute_on_all_members(self, task): """ Executes a task on all of the known cluster members. :param task: (Task), the task executed on the all of the members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member. """ return self.execute_on_members(self._client.cluster.get_member_list(), task)
[ "def", "execute_on_all_members", "(", "self", ",", "task", ")", ":", "return", "self", ".", "execute_on_members", "(", "self", ".", "_client", ".", "cluster", ".", "get_member_list", "(", ")", ",", "task", ")" ]
Executes a task on all of the known cluster members. :param task: (Task), the task executed on the all of the members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member.
[ "Executes", "a", "task", "on", "all", "of", "the", "known", "cluster", "members", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/executor.py#L60-L67
train
230,760
hazelcast/hazelcast-python-client
hazelcast/lifecycle.py
LifecycleService.add_listener
def add_listener(self, on_lifecycle_change): """ Add a listener object to listen for lifecycle events. :param on_lifecycle_change: (Function), function to be called when LifeCycle state is changed. :return: (str), id of the listener. """ id = str(uuid.uuid4()) self._listeners[id] = on_lifecycle_change return id
python
def add_listener(self, on_lifecycle_change): """ Add a listener object to listen for lifecycle events. :param on_lifecycle_change: (Function), function to be called when LifeCycle state is changed. :return: (str), id of the listener. """ id = str(uuid.uuid4()) self._listeners[id] = on_lifecycle_change return id
[ "def", "add_listener", "(", "self", ",", "on_lifecycle_change", ")", ":", "id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "self", ".", "_listeners", "[", "id", "]", "=", "on_lifecycle_change", "return", "id" ]
Add a listener object to listen for lifecycle events. :param on_lifecycle_change: (Function), function to be called when LifeCycle state is changed. :return: (str), id of the listener.
[ "Add", "a", "listener", "object", "to", "listen", "for", "lifecycle", "events", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/lifecycle.py#L31-L40
train
230,761
hazelcast/hazelcast-python-client
hazelcast/lifecycle.py
LifecycleService.remove_listener
def remove_listener(self, registration_id): """ Removes a lifecycle listener. :param registration_id: (str), the id of the listener to be removed. :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise. """ try: self._listeners.pop(registration_id) return True except KeyError: return False
python
def remove_listener(self, registration_id): """ Removes a lifecycle listener. :param registration_id: (str), the id of the listener to be removed. :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise. """ try: self._listeners.pop(registration_id) return True except KeyError: return False
[ "def", "remove_listener", "(", "self", ",", "registration_id", ")", ":", "try", ":", "self", ".", "_listeners", ".", "pop", "(", "registration_id", ")", "return", "True", "except", "KeyError", ":", "return", "False" ]
Removes a lifecycle listener. :param registration_id: (str), the id of the listener to be removed. :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise.
[ "Removes", "a", "lifecycle", "listener", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/lifecycle.py#L42-L53
train
230,762
hazelcast/hazelcast-python-client
hazelcast/lifecycle.py
LifecycleService.fire_lifecycle_event
def fire_lifecycle_event(self, new_state): """ Called when instance's state changes. :param new_state: (Lifecycle State), the new state of the instance. """ if new_state == LIFECYCLE_STATE_SHUTTING_DOWN: self.is_live = False self.state = new_state self.logger.info(self._git_info + "HazelcastClient is %s", new_state, extra=self._logger_extras) for listener in list(self._listeners.values()): try: listener(new_state) except: self.logger.exception("Exception in lifecycle listener", extra=self._logger_extras)
python
def fire_lifecycle_event(self, new_state): """ Called when instance's state changes. :param new_state: (Lifecycle State), the new state of the instance. """ if new_state == LIFECYCLE_STATE_SHUTTING_DOWN: self.is_live = False self.state = new_state self.logger.info(self._git_info + "HazelcastClient is %s", new_state, extra=self._logger_extras) for listener in list(self._listeners.values()): try: listener(new_state) except: self.logger.exception("Exception in lifecycle listener", extra=self._logger_extras)
[ "def", "fire_lifecycle_event", "(", "self", ",", "new_state", ")", ":", "if", "new_state", "==", "LIFECYCLE_STATE_SHUTTING_DOWN", ":", "self", ".", "is_live", "=", "False", "self", ".", "state", "=", "new_state", "self", ".", "logger", ".", "info", "(", "sel...
Called when instance's state changes. :param new_state: (Lifecycle State), the new state of the instance.
[ "Called", "when", "instance", "s", "state", "changes", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/lifecycle.py#L55-L70
train
230,763
hazelcast/hazelcast-python-client
hazelcast/proxy/lock.py
Lock.lock
def lock(self, lease_time=-1): """ Acquires the lock. If a lease time is specified, lock will be released after this lease time. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. :param lease_time: (long), time to wait before releasing the lock (optional). """ return self._encode_invoke(lock_lock_codec, invocation_timeout=MAX_SIZE, lease_time=to_millis(lease_time), thread_id=thread_id(), reference_id=self.reference_id_generator.get_and_increment())
python
def lock(self, lease_time=-1): """ Acquires the lock. If a lease time is specified, lock will be released after this lease time. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. :param lease_time: (long), time to wait before releasing the lock (optional). """ return self._encode_invoke(lock_lock_codec, invocation_timeout=MAX_SIZE, lease_time=to_millis(lease_time), thread_id=thread_id(), reference_id=self.reference_id_generator.get_and_increment())
[ "def", "lock", "(", "self", ",", "lease_time", "=", "-", "1", ")", ":", "return", "self", ".", "_encode_invoke", "(", "lock_lock_codec", ",", "invocation_timeout", "=", "MAX_SIZE", ",", "lease_time", "=", "to_millis", "(", "lease_time", ")", ",", "thread_id"...
Acquires the lock. If a lease time is specified, lock will be released after this lease time. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. :param lease_time: (long), time to wait before releasing the lock (optional).
[ "Acquires", "the", "lock", ".", "If", "a", "lease", "time", "is", "specified", "lock", "will", "be", "released", "after", "this", "lease", "time", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/lock.py#L58-L68
train
230,764
hazelcast/hazelcast-python-client
hazelcast/proxy/lock.py
Lock.try_lock
def try_lock(self, timeout=0, lease_time=-1): """ Tries to acquire the lock. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease time is provided, lock will be released after this time elapses. :param timeout: (long), maximum time in seconds to wait for the lock (optional). :param lease_time: (long), time in seconds to wait before releasing the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, ``false``. """ return self._encode_invoke(lock_try_lock_codec, invocation_timeout=MAX_SIZE, lease=to_millis(lease_time), thread_id=thread_id(), timeout=to_millis(timeout), reference_id=self.reference_id_generator.get_and_increment())
python
def try_lock(self, timeout=0, lease_time=-1): """ Tries to acquire the lock. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease time is provided, lock will be released after this time elapses. :param timeout: (long), maximum time in seconds to wait for the lock (optional). :param lease_time: (long), time in seconds to wait before releasing the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, ``false``. """ return self._encode_invoke(lock_try_lock_codec, invocation_timeout=MAX_SIZE, lease=to_millis(lease_time), thread_id=thread_id(), timeout=to_millis(timeout), reference_id=self.reference_id_generator.get_and_increment())
[ "def", "try_lock", "(", "self", ",", "timeout", "=", "0", ",", "lease_time", "=", "-", "1", ")", ":", "return", "self", ".", "_encode_invoke", "(", "lock_try_lock_codec", ",", "invocation_timeout", "=", "MAX_SIZE", ",", "lease", "=", "to_millis", "(", "lea...
Tries to acquire the lock. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease time is provided, lock will be released after this time elapses. :param timeout: (long), maximum time in seconds to wait for the lock (optional). :param lease_time: (long), time in seconds to wait before releasing the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, ``false``.
[ "Tries", "to", "acquire", "the", "lock", ".", "When", "the", "lock", "is", "not", "available" ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/lock.py#L70-L88
train
230,765
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.contains_key
def contains_key(self, key): """ Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ``true`` if this multimap contains an entry for the specified key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_contains_key_codec, key_data, key=key_data, thread_id=thread_id())
python
def contains_key(self, key): """ Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ``true`` if this multimap contains an entry for the specified key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_contains_key_codec, key_data, key=key_data, thread_id=thread_id())
[ "def", "contains_key", "(", "self", ",", "key", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "return", "self", ".", "_encode_invoke_on_key", "(", "multi_map_contains_key_cod...
Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ``true`` if this multimap contains an entry for the specified key.
[ "Determines", "whether", "this", "multimap", "contains", "an", "entry", "with", "the", "key", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L55-L68
train
230,766
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.contains_entry
def contains_entry(self, key, value): """ Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple. """ check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_contains_entry_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
python
def contains_entry(self, key, value): """ Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple. """ check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_contains_entry_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
[ "def", "contains_entry", "(", "self", ",", "key", ",", "value", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "check_not_none", "(", "value", ",", "\"value can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key"...
Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple.
[ "Returns", "whether", "the", "multimap", "contains", "an", "entry", "with", "the", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L81-L94
train
230,767
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.get
def get(self, key): """ Returns the list of values associated with the key. ``None`` if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** **Warning-2: The list is NOT backed by the multimap, so changes to the map are list reflected in the collection, and vice-versa.** :param key: (object), the specified key. :return: (Sequence), the list of the values associated with the specified key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_get_codec, key_data, key=key_data, thread_id=thread_id())
python
def get(self, key): """ Returns the list of values associated with the key. ``None`` if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** **Warning-2: The list is NOT backed by the multimap, so changes to the map are list reflected in the collection, and vice-versa.** :param key: (object), the specified key. :return: (Sequence), the list of the values associated with the specified key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_get_codec, key_data, key=key_data, thread_id=thread_id())
[ "def", "get", "(", "self", ",", "key", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "return", "self", ".", "_encode_invoke_on_key", "(", "multi_map_get_codec", ",", "key...
Returns the list of values associated with the key. ``None`` if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** **Warning-2: The list is NOT backed by the multimap, so changes to the map are list reflected in the collection, and vice-versa.** :param key: (object), the specified key. :return: (Sequence), the list of the values associated with the specified key.
[ "Returns", "the", "list", "of", "values", "associated", "with", "the", "key", ".", "None", "if", "this", "map", "does", "not", "contain", "this", "key", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L113-L131
train
230,768
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.is_locked
def is_locked(self, key): """ Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key that is checked for lock. :return: (bool), ``true`` if lock is acquired, false otherwise. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_is_locked_codec, key_data, key=key_data)
python
def is_locked(self, key): """ Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key that is checked for lock. :return: (bool), ``true`` if lock is acquired, false otherwise. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_is_locked_codec, key_data, key=key_data)
[ "def", "is_locked", "(", "self", ",", "key", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "return", "self", ".", "_encode_invoke_on_key", "(", "multi_map_is_locked_codec", ...
Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key that is checked for lock. :return: (bool), ``true`` if lock is acquired, false otherwise.
[ "Checks", "the", "lock", "for", "the", "specified", "key", ".", "If", "the", "lock", "is", "acquired", "returns", "true", ".", "Otherwise", "returns", "false", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L133-L145
train
230,769
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.remove
def remove(self, key, value): """ Removes the given key-value tuple from the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: (bool), ``true`` if the size of the multimap changed after the remove operation, ``false`` otherwise. """ check_not_none(key, "key can't be None") check_not_none(key, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_remove_entry_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
python
def remove(self, key, value): """ Removes the given key-value tuple from the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: (bool), ``true`` if the size of the multimap changed after the remove operation, ``false`` otherwise. """ check_not_none(key, "key can't be None") check_not_none(key, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_remove_entry_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
[ "def", "remove", "(", "self", ",", "key", ",", "value", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "check_not_none", "(", "key", ",", "\"value can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", ...
Removes the given key-value tuple from the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: (bool), ``true`` if the size of the multimap changed after the remove operation, ``false`` otherwise.
[ "Removes", "the", "given", "key", "-", "value", "tuple", "from", "the", "multimap", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L197-L213
train
230,770
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.remove_all
def remove_all(self, key): """ Removes all the entries with the given key and returns the value list associated with this key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** **Warning-2: The returned list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param key: (object), the key of the entries to remove. :return: (Sequence), the collection of removed values associated with the given key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_remove_codec, key_data, key=key_data, thread_id=thread_id())
python
def remove_all(self, key): """ Removes all the entries with the given key and returns the value list associated with this key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** **Warning-2: The returned list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param key: (object), the key of the entries to remove. :return: (Sequence), the collection of removed values associated with the given key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_remove_codec, key_data, key=key_data, thread_id=thread_id())
[ "def", "remove_all", "(", "self", ",", "key", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "return", "self", ".", "_encode_invoke_on_key", "(", "multi_map_remove_codec", "...
Removes all the entries with the given key and returns the value list associated with this key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** **Warning-2: The returned list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param key: (object), the key of the entries to remove. :return: (Sequence), the collection of removed values associated with the given key.
[ "Removes", "all", "the", "entries", "with", "the", "given", "key", "and", "returns", "the", "value", "list", "associated", "with", "this", "key", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L215-L232
train
230,771
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.put
def put(self, key, value): """ Stores a key-value tuple in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple. """ check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_put_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
python
def put(self, key, value): """ Stores a key-value tuple in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple. """ check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_put_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
[ "def", "put", "(", "self", ",", "key", ",", "value", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "check_not_none", "(", "value", ",", "\"value can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", ...
Stores a key-value tuple in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple.
[ "Stores", "a", "key", "-", "value", "tuple", "in", "the", "multimap", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L234-L251
train
230,772
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
MultiMap.value_count
def value_count(self, key): """ Returns the number of values that match the given key in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key whose values count is to be returned. :return: (int), the number of values that match the given key in the multimap. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_value_count_codec, key_data, key=key_data, thread_id=thread_id())
python
def value_count(self, key): """ Returns the number of values that match the given key in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key whose values count is to be returned. :return: (int), the number of values that match the given key in the multimap. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_value_count_codec, key_data, key=key_data, thread_id=thread_id())
[ "def", "value_count", "(", "self", ",", "key", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "return", "self", ".", "_encode_invoke_on_key", "(", "multi_map_value_count_codec...
Returns the number of values that match the given key in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key whose values count is to be returned. :return: (int), the number of values that match the given key in the multimap.
[ "Returns", "the", "number", "of", "values", "that", "match", "the", "given", "key", "in", "the", "multimap", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L271-L284
train
230,773
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.alter
def alter(self, function): """ Alters the currently stored reference by applying a function on it. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_alter_codec, function=self._to_data(function))
python
def alter(self, function): """ Alters the currently stored reference by applying a function on it. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_alter_codec, function=self._to_data(function))
[ "def", "alter", "(", "self", ",", "function", ")", ":", "check_not_none", "(", "function", ",", "\"function can't be None\"", ")", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_alter_codec", ",", "function", "=", "self", ".", "_to_data", "(", "...
Alters the currently stored reference by applying a function on it. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation.
[ "Alters", "the", "currently", "stored", "reference", "by", "applying", "a", "function", "on", "it", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L14-L24
train
230,774
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.alter_and_get
def alter_and_get(self, function): """ Alters the currently stored reference by applying a function on it and gets the result. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the new value, the result of the applied function. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_alter_and_get_codec, function=self._to_data(function))
python
def alter_and_get(self, function): """ Alters the currently stored reference by applying a function on it and gets the result. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the new value, the result of the applied function. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_alter_and_get_codec, function=self._to_data(function))
[ "def", "alter_and_get", "(", "self", ",", "function", ")", ":", "check_not_none", "(", "function", ",", "\"function can't be None\"", ")", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_alter_and_get_codec", ",", "function", "=", "self", ".", "_to_d...
Alters the currently stored reference by applying a function on it and gets the result. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the new value, the result of the applied function.
[ "Alters", "the", "currently", "stored", "reference", "by", "applying", "a", "function", "on", "it", "and", "gets", "the", "result", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L39-L50
train
230,775
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.contains
def contains(self, expected): """ Checks if the reference contains the value. :param expected: (object), the value to check (is allowed to be ``None``). :return: (bool), ``true`` if the value is found, ``false`` otherwise. """ return self._encode_invoke(atomic_reference_contains_codec, expected=self._to_data(expected))
python
def contains(self, expected): """ Checks if the reference contains the value. :param expected: (object), the value to check (is allowed to be ``None``). :return: (bool), ``true`` if the value is found, ``false`` otherwise. """ return self._encode_invoke(atomic_reference_contains_codec, expected=self._to_data(expected))
[ "def", "contains", "(", "self", ",", "expected", ")", ":", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_contains_codec", ",", "expected", "=", "self", ".", "_to_data", "(", "expected", ")", ")" ]
Checks if the reference contains the value. :param expected: (object), the value to check (is allowed to be ``None``). :return: (bool), ``true`` if the value is found, ``false`` otherwise.
[ "Checks", "if", "the", "reference", "contains", "the", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L69-L78
train
230,776
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.get_and_alter
def get_and_alter(self, function): """ Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the old value, the value before the function is applied. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_get_and_alter_codec, function=self._to_data(function))
python
def get_and_alter(self, function): """ Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the old value, the value before the function is applied. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_get_and_alter_codec, function=self._to_data(function))
[ "def", "get_and_alter", "(", "self", ",", "function", ")", ":", "check_not_none", "(", "function", ",", "\"function can't be None\"", ")", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_get_and_alter_codec", ",", "function", "=", "self", ".", "_to_d...
Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the old value, the value before the function is applied.
[ "Alters", "the", "currently", "stored", "reference", "by", "applying", "a", "function", "on", "it", "on", "and", "gets", "the", "old", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L88-L100
train
230,777
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.get_and_set
def get_and_set(self, new_value): """ Gets the old value and sets the new value. :param new_value: (object), the new value. :return: (object), the old value. """ return self._encode_invoke(atomic_reference_get_and_set_codec, new_value=self._to_data(new_value))
python
def get_and_set(self, new_value): """ Gets the old value and sets the new value. :param new_value: (object), the new value. :return: (object), the old value. """ return self._encode_invoke(atomic_reference_get_and_set_codec, new_value=self._to_data(new_value))
[ "def", "get_and_set", "(", "self", ",", "new_value", ")", ":", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_get_and_set_codec", ",", "new_value", "=", "self", ".", "_to_data", "(", "new_value", ")", ")" ]
Gets the old value and sets the new value. :param new_value: (object), the new value. :return: (object), the old value.
[ "Gets", "the", "old", "value", "and", "sets", "the", "new", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L102-L110
train
230,778
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.set
def set(self, new_value): """ Atomically sets the given value. :param new_value: (object), the new value. """ return self._encode_invoke(atomic_reference_set_codec, new_value=self._to_data(new_value))
python
def set(self, new_value): """ Atomically sets the given value. :param new_value: (object), the new value. """ return self._encode_invoke(atomic_reference_set_codec, new_value=self._to_data(new_value))
[ "def", "set", "(", "self", ",", "new_value", ")", ":", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_set_codec", ",", "new_value", "=", "self", ".", "_to_data", "(", "new_value", ")", ")" ]
Atomically sets the given value. :param new_value: (object), the new value.
[ "Atomically", "sets", "the", "given", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L120-L127
train
230,779
hazelcast/hazelcast-python-client
hazelcast/proxy/atomic_reference.py
AtomicReference.set_and_get
def set_and_get(self, new_value): """ Sets and gets the value. :param new_value: (object), the new value. :return: (object), the new value. """ return self._encode_invoke(atomic_reference_set_and_get_codec, new_value=self._to_data(new_value))
python
def set_and_get(self, new_value): """ Sets and gets the value. :param new_value: (object), the new value. :return: (object), the new value. """ return self._encode_invoke(atomic_reference_set_and_get_codec, new_value=self._to_data(new_value))
[ "def", "set_and_get", "(", "self", ",", "new_value", ")", ":", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_set_and_get_codec", ",", "new_value", "=", "self", ".", "_to_data", "(", "new_value", ")", ")" ]
Sets and gets the value. :param new_value: (object), the new value. :return: (object), the new value.
[ "Sets", "and", "gets", "the", "value", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/atomic_reference.py#L129-L137
train
230,780
hazelcast/hazelcast-python-client
hazelcast/serialization/data.py
Data.get_type
def get_type(self): """ Returns serialization type of binary form. :return: Serialization type of binary form. """ if self.total_size() == 0: return CONSTANT_TYPE_NULL return unpack_from(FMT_BE_INT, self._buffer, TYPE_OFFSET)[0]
python
def get_type(self): """ Returns serialization type of binary form. :return: Serialization type of binary form. """ if self.total_size() == 0: return CONSTANT_TYPE_NULL return unpack_from(FMT_BE_INT, self._buffer, TYPE_OFFSET)[0]
[ "def", "get_type", "(", "self", ")", ":", "if", "self", ".", "total_size", "(", ")", "==", "0", ":", "return", "CONSTANT_TYPE_NULL", "return", "unpack_from", "(", "FMT_BE_INT", ",", "self", ".", "_buffer", ",", "TYPE_OFFSET", ")", "[", "0", "]" ]
Returns serialization type of binary form. :return: Serialization type of binary form.
[ "Returns", "serialization", "type", "of", "binary", "form", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/serialization/data.py#L30-L38
train
230,781
hazelcast/hazelcast-python-client
hazelcast/serialization/data.py
Data.has_partition_hash
def has_partition_hash(self): """ Determines whether this Data has partition hash or not. :return: (bool), ``true`` if Data has partition hash, ``false`` otherwise. """ return self._buffer is not None \ and len(self._buffer) >= HEAP_DATA_OVERHEAD \ and unpack_from(FMT_BE_INT, self._buffer, PARTITION_HASH_OFFSET)[0] != 0
python
def has_partition_hash(self): """ Determines whether this Data has partition hash or not. :return: (bool), ``true`` if Data has partition hash, ``false`` otherwise. """ return self._buffer is not None \ and len(self._buffer) >= HEAP_DATA_OVERHEAD \ and unpack_from(FMT_BE_INT, self._buffer, PARTITION_HASH_OFFSET)[0] != 0
[ "def", "has_partition_hash", "(", "self", ")", ":", "return", "self", ".", "_buffer", "is", "not", "None", "and", "len", "(", "self", ".", "_buffer", ")", ">=", "HEAP_DATA_OVERHEAD", "and", "unpack_from", "(", "FMT_BE_INT", ",", "self", ".", "_buffer", ","...
Determines whether this Data has partition hash or not. :return: (bool), ``true`` if Data has partition hash, ``false`` otherwise.
[ "Determines", "whether", "this", "Data", "has", "partition", "hash", "or", "not", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/serialization/data.py#L77-L85
train
230,782
hazelcast/hazelcast-python-client
hazelcast/serialization/base.py
SerializerRegistry.serializer_for
def serializer_for(self, obj): """ Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types by user 4-Global serializer if registered by user 4-pickle serialization as a fallback :param obj: input object :return: Serializer """ # 1-NULL serializer if obj is None: return self._null_serializer obj_type = type(obj) # 2-Default serializers, Dataserializable, Portable, primitives, arrays, String and some helper types(BigInteger etc) serializer = self.lookup_default_serializer(obj_type, obj) # 3-Custom registered types by user if serializer is None: serializer = self.lookup_custom_serializer(obj_type) # 5-Global serializer if registered by user if serializer is None: serializer = self.lookup_global_serializer(obj_type) # 4 Internal serializer if serializer is None: serializer = self.lookup_python_serializer(obj_type) if serializer is None: raise HazelcastSerializationError("There is no suitable serializer for:" + str(obj_type)) return serializer
python
def serializer_for(self, obj): """ Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types by user 4-Global serializer if registered by user 4-pickle serialization as a fallback :param obj: input object :return: Serializer """ # 1-NULL serializer if obj is None: return self._null_serializer obj_type = type(obj) # 2-Default serializers, Dataserializable, Portable, primitives, arrays, String and some helper types(BigInteger etc) serializer = self.lookup_default_serializer(obj_type, obj) # 3-Custom registered types by user if serializer is None: serializer = self.lookup_custom_serializer(obj_type) # 5-Global serializer if registered by user if serializer is None: serializer = self.lookup_global_serializer(obj_type) # 4 Internal serializer if serializer is None: serializer = self.lookup_python_serializer(obj_type) if serializer is None: raise HazelcastSerializationError("There is no suitable serializer for:" + str(obj_type)) return serializer
[ "def", "serializer_for", "(", "self", ",", "obj", ")", ":", "# 1-NULL serializer", "if", "obj", "is", "None", ":", "return", "self", ".", "_null_serializer", "obj_type", "=", "type", "(", "obj", ")", "# 2-Default serializers, Dataserializable, Portable, primitives, ar...
Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types by user 4-Global serializer if registered by user 4-pickle serialization as a fallback :param obj: input object :return: Serializer
[ "Searches", "for", "a", "serializer", "for", "the", "provided", "object", "Serializers", "will", "be", "searched", "in", "this", "order", ";" ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/serialization/base.py#L182-L219
train
230,783
hazelcast/hazelcast-python-client
hazelcast/near_cache.py
DataRecord.is_expired
def is_expired(self, max_idle_seconds): """ Determines whether this record is expired or not. :param max_idle_seconds: (long), the maximum idle time of record, maximum time after the last access time. :return: (bool), ``true`` is this record is not expired. """ now = current_time() return (self.expiration_time is not None and self.expiration_time < now) or \ (max_idle_seconds is not None and self.last_access_time + max_idle_seconds < now)
python
def is_expired(self, max_idle_seconds): """ Determines whether this record is expired or not. :param max_idle_seconds: (long), the maximum idle time of record, maximum time after the last access time. :return: (bool), ``true`` is this record is not expired. """ now = current_time() return (self.expiration_time is not None and self.expiration_time < now) or \ (max_idle_seconds is not None and self.last_access_time + max_idle_seconds < now)
[ "def", "is_expired", "(", "self", ",", "max_idle_seconds", ")", ":", "now", "=", "current_time", "(", ")", "return", "(", "self", ".", "expiration_time", "is", "not", "None", "and", "self", ".", "expiration_time", "<", "now", ")", "or", "(", "max_idle_seco...
Determines whether this record is expired or not. :param max_idle_seconds: (long), the maximum idle time of record, maximum time after the last access time. :return: (bool), ``true`` is this record is not expired.
[ "Determines", "whether", "this", "record", "is", "expired", "or", "not", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/near_cache.py#L56-L66
train
230,784
hazelcast/hazelcast-python-client
hazelcast/future.py
combine_futures
def combine_futures(*futures): """ Combines set of Futures. :param futures: (Futures), Futures to be combined. :return: Result of the combination. """ expected = len(futures) results = [] completed = AtomicInteger() combined = Future() def done(f): if not combined.done(): if f.is_success(): # TODO: ensure ordering of results as original list results.append(f.result()) if completed.get_and_increment() + 1 == expected: combined.set_result(results) else: combined.set_exception(f.exception(), f.traceback()) for future in futures: future.add_done_callback(done) return combined
python
def combine_futures(*futures): """ Combines set of Futures. :param futures: (Futures), Futures to be combined. :return: Result of the combination. """ expected = len(futures) results = [] completed = AtomicInteger() combined = Future() def done(f): if not combined.done(): if f.is_success(): # TODO: ensure ordering of results as original list results.append(f.result()) if completed.get_and_increment() + 1 == expected: combined.set_result(results) else: combined.set_exception(f.exception(), f.traceback()) for future in futures: future.add_done_callback(done) return combined
[ "def", "combine_futures", "(", "*", "futures", ")", ":", "expected", "=", "len", "(", "futures", ")", "results", "=", "[", "]", "completed", "=", "AtomicInteger", "(", ")", "combined", "=", "Future", "(", ")", "def", "done", "(", "f", ")", ":", "if",...
Combines set of Futures. :param futures: (Futures), Futures to be combined. :return: Result of the combination.
[ "Combines", "set", "of", "Futures", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/future.py#L233-L257
train
230,785
hazelcast/hazelcast-python-client
hazelcast/future.py
Future.set_result
def set_result(self, result): """ Sets the result of the Future. :param result: Result of the Future. """ if result is None: self._result = NONE_RESULT else: self._result = result self._event.set() self._invoke_callbacks()
python
def set_result(self, result): """ Sets the result of the Future. :param result: Result of the Future. """ if result is None: self._result = NONE_RESULT else: self._result = result self._event.set() self._invoke_callbacks()
[ "def", "set_result", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "self", ".", "_result", "=", "NONE_RESULT", "else", ":", "self", ".", "_result", "=", "result", "self", ".", "_event", ".", "set", "(", ")", "self", ".", ...
Sets the result of the Future. :param result: Result of the Future.
[ "Sets", "the", "result", "of", "the", "Future", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/future.py#L25-L36
train
230,786
hazelcast/hazelcast-python-client
hazelcast/future.py
Future.set_exception
def set_exception(self, exception, traceback=None): """ Sets the exception for this Future in case of errors. :param exception: (Exception), exception to be threw in case of error. :param traceback: (Function), function to be called on traceback (optional). """ if not isinstance(exception, BaseException): raise RuntimeError("Exception must be of BaseException type") self._exception = exception self._traceback = traceback self._event.set() self._invoke_callbacks()
python
def set_exception(self, exception, traceback=None): """ Sets the exception for this Future in case of errors. :param exception: (Exception), exception to be threw in case of error. :param traceback: (Function), function to be called on traceback (optional). """ if not isinstance(exception, BaseException): raise RuntimeError("Exception must be of BaseException type") self._exception = exception self._traceback = traceback self._event.set() self._invoke_callbacks()
[ "def", "set_exception", "(", "self", ",", "exception", ",", "traceback", "=", "None", ")", ":", "if", "not", "isinstance", "(", "exception", ",", "BaseException", ")", ":", "raise", "RuntimeError", "(", "\"Exception must be of BaseException type\"", ")", "self", ...
Sets the exception for this Future in case of errors. :param exception: (Exception), exception to be threw in case of error. :param traceback: (Function), function to be called on traceback (optional).
[ "Sets", "the", "exception", "for", "this", "Future", "in", "case", "of", "errors", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/future.py#L38-L50
train
230,787
hazelcast/hazelcast-python-client
hazelcast/future.py
Future.result
def result(self): """ Returns the result of the Future, which makes the call synchronous if the result has not been computed yet. :return: Result of the Future. """ self._reactor_check() self._event.wait() if self._exception: six.reraise(self._exception.__class__, self._exception, self._traceback) if self._result == NONE_RESULT: return None else: return self._result
python
def result(self): """ Returns the result of the Future, which makes the call synchronous if the result has not been computed yet. :return: Result of the Future. """ self._reactor_check() self._event.wait() if self._exception: six.reraise(self._exception.__class__, self._exception, self._traceback) if self._result == NONE_RESULT: return None else: return self._result
[ "def", "result", "(", "self", ")", ":", "self", ".", "_reactor_check", "(", ")", "self", ".", "_event", ".", "wait", "(", ")", "if", "self", ".", "_exception", ":", "six", ".", "reraise", "(", "self", ".", "_exception", ".", "__class__", ",", "self",...
Returns the result of the Future, which makes the call synchronous if the result has not been computed yet. :return: Result of the Future.
[ "Returns", "the", "result", "of", "the", "Future", "which", "makes", "the", "call", "synchronous", "if", "the", "result", "has", "not", "been", "computed", "yet", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/future.py#L52-L65
train
230,788
hazelcast/hazelcast-python-client
hazelcast/future.py
Future.continue_with
def continue_with(self, continuation_func, *args): """ Create a continuation that executes when the Future is completed. :param continuation_func: A function which takes the future as the only parameter. Return value of the function will be set as the result of the continuation future. :return: A new Future which will be completed when the continuation is done. """ future = Future() def callback(f): try: future.set_result(continuation_func(f, *args)) except: future.set_exception(sys.exc_info()[1], sys.exc_info()[2]) self.add_done_callback(callback) return future
python
def continue_with(self, continuation_func, *args): """ Create a continuation that executes when the Future is completed. :param continuation_func: A function which takes the future as the only parameter. Return value of the function will be set as the result of the continuation future. :return: A new Future which will be completed when the continuation is done. """ future = Future() def callback(f): try: future.set_result(continuation_func(f, *args)) except: future.set_exception(sys.exc_info()[1], sys.exc_info()[2]) self.add_done_callback(callback) return future
[ "def", "continue_with", "(", "self", ",", "continuation_func", ",", "*", "args", ")", ":", "future", "=", "Future", "(", ")", "def", "callback", "(", "f", ")", ":", "try", ":", "future", ".", "set_result", "(", "continuation_func", "(", "f", ",", "*", ...
Create a continuation that executes when the Future is completed. :param continuation_func: A function which takes the future as the only parameter. Return value of the function will be set as the result of the continuation future. :return: A new Future which will be completed when the continuation is done.
[ "Create", "a", "continuation", "that", "executes", "when", "the", "Future", "is", "completed", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/future.py#L133-L150
train
230,789
hazelcast/hazelcast-python-client
hazelcast/connection.py
ConnectionManager.on_auth
def on_auth(self, f, connection, address): """ Checks for authentication of a connection. :param f: (:class:`~hazelcast.future.Future`), future that contains the result of authentication. :param connection: (:class:`~hazelcast.connection.Connection`), newly established connection. :param address: (:class:`~hazelcast.core.Address`), the adress of new connection. :return: Result of authentication. """ if f.is_success(): self.logger.info("Authenticated with %s", f.result(), extra=self._logger_extras) with self._new_connection_mutex: self.connections[connection.endpoint] = f.result() try: self._pending_connections.pop(address) except KeyError: pass for on_connection_opened, _ in self._connection_listeners: if on_connection_opened: on_connection_opened(f.result()) return f.result() else: self.logger.debug("Error opening %s", connection, extra=self._logger_extras) with self._new_connection_mutex: try: self._pending_connections.pop(address) except KeyError: pass six.reraise(f.exception().__class__, f.exception(), f.traceback())
python
def on_auth(self, f, connection, address): """ Checks for authentication of a connection. :param f: (:class:`~hazelcast.future.Future`), future that contains the result of authentication. :param connection: (:class:`~hazelcast.connection.Connection`), newly established connection. :param address: (:class:`~hazelcast.core.Address`), the adress of new connection. :return: Result of authentication. """ if f.is_success(): self.logger.info("Authenticated with %s", f.result(), extra=self._logger_extras) with self._new_connection_mutex: self.connections[connection.endpoint] = f.result() try: self._pending_connections.pop(address) except KeyError: pass for on_connection_opened, _ in self._connection_listeners: if on_connection_opened: on_connection_opened(f.result()) return f.result() else: self.logger.debug("Error opening %s", connection, extra=self._logger_extras) with self._new_connection_mutex: try: self._pending_connections.pop(address) except KeyError: pass six.reraise(f.exception().__class__, f.exception(), f.traceback())
[ "def", "on_auth", "(", "self", ",", "f", ",", "connection", ",", "address", ")", ":", "if", "f", ".", "is_success", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Authenticated with %s\"", ",", "f", ".", "result", "(", ")", ",", "extra", ...
Checks for authentication of a connection. :param f: (:class:`~hazelcast.future.Future`), future that contains the result of authentication. :param connection: (:class:`~hazelcast.connection.Connection`), newly established connection. :param address: (:class:`~hazelcast.core.Address`), the adress of new connection. :return: Result of authentication.
[ "Checks", "for", "authentication", "of", "a", "connection", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/connection.py#L123-L151
train
230,790
hazelcast/hazelcast-python-client
hazelcast/connection.py
ConnectionManager.close_connection
def close_connection(self, address, cause): """ Closes the connection with given address. :param address: (:class:`~hazelcast.core.Address`), address of the connection to be closed. :param cause: (Exception), the cause for closing the connection. :return: (bool), ``true`` if the connection is closed, ``false`` otherwise. """ try: connection = self.connections[address] connection.close(cause) except KeyError: self.logger.warning("No connection with %s was found to close.", address, extra=self._logger_extras) return False
python
def close_connection(self, address, cause): """ Closes the connection with given address. :param address: (:class:`~hazelcast.core.Address`), address of the connection to be closed. :param cause: (Exception), the cause for closing the connection. :return: (bool), ``true`` if the connection is closed, ``false`` otherwise. """ try: connection = self.connections[address] connection.close(cause) except KeyError: self.logger.warning("No connection with %s was found to close.", address, extra=self._logger_extras) return False
[ "def", "close_connection", "(", "self", ",", "address", ",", "cause", ")", ":", "try", ":", "connection", "=", "self", ".", "connections", "[", "address", "]", "connection", ".", "close", "(", "cause", ")", "except", "KeyError", ":", "self", ".", "logger...
Closes the connection with given address. :param address: (:class:`~hazelcast.core.Address`), address of the connection to be closed. :param cause: (Exception), the cause for closing the connection. :return: (bool), ``true`` if the connection is closed, ``false`` otherwise.
[ "Closes", "the", "connection", "with", "given", "address", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/connection.py#L167-L180
train
230,791
hazelcast/hazelcast-python-client
hazelcast/connection.py
Heartbeat.start
def start(self): """ Starts sending periodic HeartBeat operations. """ def _heartbeat(): if not self._client.lifecycle.is_live: return self._heartbeat() self._heartbeat_timer = self._client.reactor.add_timer(self._heartbeat_interval, _heartbeat) self._heartbeat_timer = self._client.reactor.add_timer(self._heartbeat_interval, _heartbeat)
python
def start(self): """ Starts sending periodic HeartBeat operations. """ def _heartbeat(): if not self._client.lifecycle.is_live: return self._heartbeat() self._heartbeat_timer = self._client.reactor.add_timer(self._heartbeat_interval, _heartbeat) self._heartbeat_timer = self._client.reactor.add_timer(self._heartbeat_interval, _heartbeat)
[ "def", "start", "(", "self", ")", ":", "def", "_heartbeat", "(", ")", ":", "if", "not", "self", ".", "_client", ".", "lifecycle", ".", "is_live", ":", "return", "self", ".", "_heartbeat", "(", ")", "self", ".", "_heartbeat_timer", "=", "self", ".", "...
Starts sending periodic HeartBeat operations.
[ "Starts", "sending", "periodic", "HeartBeat", "operations", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/connection.py#L198-L208
train
230,792
hazelcast/hazelcast-python-client
hazelcast/connection.py
Connection.send_message
def send_message(self, message): """ Sends a message to this connection. :param message: (Message), message to be sent to this connection. """ if not self.live(): raise IOError("Connection is not live.") message.add_flag(BEGIN_END_FLAG) self.write(message.buffer)
python
def send_message(self, message): """ Sends a message to this connection. :param message: (Message), message to be sent to this connection. """ if not self.live(): raise IOError("Connection is not live.") message.add_flag(BEGIN_END_FLAG) self.write(message.buffer)
[ "def", "send_message", "(", "self", ",", "message", ")", ":", "if", "not", "self", ".", "live", "(", ")", ":", "raise", "IOError", "(", "\"Connection is not live.\"", ")", "message", ".", "add_flag", "(", "BEGIN_END_FLAG", ")", "self", ".", "write", "(", ...
Sends a message to this connection. :param message: (Message), message to be sent to this connection.
[ "Sends", "a", "message", "to", "this", "connection", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/connection.py#L291-L301
train
230,793
hazelcast/hazelcast-python-client
hazelcast/connection.py
Connection.receive_message
def receive_message(self): """ Receives a message from this connection. """ # split frames while len(self._read_buffer) >= INT_SIZE_IN_BYTES: frame_length = struct.unpack_from(FMT_LE_INT, self._read_buffer, 0)[0] if frame_length > len(self._read_buffer): return message = ClientMessage(memoryview(self._read_buffer)[:frame_length]) self._read_buffer = self._read_buffer[frame_length:] self._builder.on_message(message)
python
def receive_message(self): """ Receives a message from this connection. """ # split frames while len(self._read_buffer) >= INT_SIZE_IN_BYTES: frame_length = struct.unpack_from(FMT_LE_INT, self._read_buffer, 0)[0] if frame_length > len(self._read_buffer): return message = ClientMessage(memoryview(self._read_buffer)[:frame_length]) self._read_buffer = self._read_buffer[frame_length:] self._builder.on_message(message)
[ "def", "receive_message", "(", "self", ")", ":", "# split frames", "while", "len", "(", "self", ".", "_read_buffer", ")", ">=", "INT_SIZE_IN_BYTES", ":", "frame_length", "=", "struct", ".", "unpack_from", "(", "FMT_LE_INT", ",", "self", ".", "_read_buffer", ",...
Receives a message from this connection.
[ "Receives", "a", "message", "from", "this", "connection", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/connection.py#L303-L314
train
230,794
hazelcast/hazelcast-python-client
hazelcast/proxy/semaphore.py
Semaphore.init
def init(self, permits): """ Try to initialize this Semaphore instance with the given permit count. :param permits: (int), the given permit count. :return: (bool), ``true`` if initialization success. """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_init_codec, permits=permits)
python
def init(self, permits): """ Try to initialize this Semaphore instance with the given permit count. :param permits: (int), the given permit count. :return: (bool), ``true`` if initialization success. """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_init_codec, permits=permits)
[ "def", "init", "(", "self", ",", "permits", ")", ":", "check_not_negative", "(", "permits", ",", "\"Permits cannot be negative!\"", ")", "return", "self", ".", "_encode_invoke", "(", "semaphore_init_codec", ",", "permits", "=", "permits", ")" ]
Try to initialize this Semaphore instance with the given permit count. :param permits: (int), the given permit count. :return: (bool), ``true`` if initialization success.
[ "Try", "to", "initialize", "this", "Semaphore", "instance", "with", "the", "given", "permit", "count", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/semaphore.py#L33-L41
train
230,795
hazelcast/hazelcast-python-client
hazelcast/proxy/semaphore.py
Semaphore.acquire
def acquire(self, permits=1): """ Acquires one or specified amount of permits if available, and returns immediately, reducing the number of available permits by one or given amount. If insufficient permits are available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of following happens: * some other thread invokes one of the release methods for this semaphore, the current thread is next to be assigned permits and the number of available permits satisfies this request, * this Semaphore instance is destroyed, or * some other thread interrupts the current thread. :param permits: (int), the number of permits to acquire (optional). """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_acquire_codec, permits=permits)
python
def acquire(self, permits=1): """ Acquires one or specified amount of permits if available, and returns immediately, reducing the number of available permits by one or given amount. If insufficient permits are available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of following happens: * some other thread invokes one of the release methods for this semaphore, the current thread is next to be assigned permits and the number of available permits satisfies this request, * this Semaphore instance is destroyed, or * some other thread interrupts the current thread. :param permits: (int), the number of permits to acquire (optional). """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_acquire_codec, permits=permits)
[ "def", "acquire", "(", "self", ",", "permits", "=", "1", ")", ":", "check_not_negative", "(", "permits", ",", "\"Permits cannot be negative!\"", ")", "return", "self", ".", "_encode_invoke", "(", "semaphore_acquire_codec", ",", "permits", "=", "permits", ")" ]
Acquires one or specified amount of permits if available, and returns immediately, reducing the number of available permits by one or given amount. If insufficient permits are available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of following happens: * some other thread invokes one of the release methods for this semaphore, the current thread is next to be assigned permits and the number of available permits satisfies this request, * this Semaphore instance is destroyed, or * some other thread interrupts the current thread. :param permits: (int), the number of permits to acquire (optional).
[ "Acquires", "one", "or", "specified", "amount", "of", "permits", "if", "available", "and", "returns", "immediately", "reducing", "the", "number", "of", "available", "permits", "by", "one", "or", "given", "amount", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/semaphore.py#L43-L59
train
230,796
hazelcast/hazelcast-python-client
hazelcast/proxy/semaphore.py
Semaphore.reduce_permits
def reduce_permits(self, reduction): """ Shrinks the number of available permits by the indicated reduction. This method differs from acquire in that it does not block waiting for permits to become available. :param reduction: (int), the number of permits to remove. """ check_not_negative(reduction, "Reduction cannot be negative!") return self._encode_invoke(semaphore_reduce_permits_codec, reduction=reduction)
python
def reduce_permits(self, reduction): """ Shrinks the number of available permits by the indicated reduction. This method differs from acquire in that it does not block waiting for permits to become available. :param reduction: (int), the number of permits to remove. """ check_not_negative(reduction, "Reduction cannot be negative!") return self._encode_invoke(semaphore_reduce_permits_codec, reduction=reduction)
[ "def", "reduce_permits", "(", "self", ",", "reduction", ")", ":", "check_not_negative", "(", "reduction", ",", "\"Reduction cannot be negative!\"", ")", "return", "self", ".", "_encode_invoke", "(", "semaphore_reduce_permits_codec", ",", "reduction", "=", "reduction", ...
Shrinks the number of available permits by the indicated reduction. This method differs from acquire in that it does not block waiting for permits to become available. :param reduction: (int), the number of permits to remove.
[ "Shrinks", "the", "number", "of", "available", "permits", "by", "the", "indicated", "reduction", ".", "This", "method", "differs", "from", "acquire", "in", "that", "it", "does", "not", "block", "waiting", "for", "permits", "to", "become", "available", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/semaphore.py#L78-L86
train
230,797
hazelcast/hazelcast-python-client
hazelcast/proxy/semaphore.py
Semaphore.release
def release(self, permits=1): """ Releases one or given number of permits, increasing the number of available permits by one or that amount. There is no requirement that a thread that releases a permit must have acquired that permit by calling one of the acquire methods. Correct usage of a semaphore is established by programming convention in the application. :param permits: (int), the number of permits to release (optional). """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_release_codec, permits=permits)
python
def release(self, permits=1): """ Releases one or given number of permits, increasing the number of available permits by one or that amount. There is no requirement that a thread that releases a permit must have acquired that permit by calling one of the acquire methods. Correct usage of a semaphore is established by programming convention in the application. :param permits: (int), the number of permits to release (optional). """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_release_codec, permits=permits)
[ "def", "release", "(", "self", ",", "permits", "=", "1", ")", ":", "check_not_negative", "(", "permits", ",", "\"Permits cannot be negative!\"", ")", "return", "self", ".", "_encode_invoke", "(", "semaphore_release_codec", ",", "permits", "=", "permits", ")" ]
Releases one or given number of permits, increasing the number of available permits by one or that amount. There is no requirement that a thread that releases a permit must have acquired that permit by calling one of the acquire methods. Correct usage of a semaphore is established by programming convention in the application. :param permits: (int), the number of permits to release (optional).
[ "Releases", "one", "or", "given", "number", "of", "permits", "increasing", "the", "number", "of", "available", "permits", "by", "one", "or", "that", "amount", "." ]
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/semaphore.py#L88-L98
train
230,798
hazelcast/hazelcast-python-client
hazelcast/proxy/semaphore.py
Semaphore.try_acquire
def try_acquire(self, permits=1, timeout=0): """ Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the value ``true``, reducing the number of available permits by the given amount. If there are insufficient permits and a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of following happens: * some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit, or * some other thread interrupts the current thread, or * the specified waiting time elapses. If there are insufficient permits and no timeout is provided, this method will return immediately with the value ``false`` and the number of available permits is unchanged. :param permits: (int), the number of permits to acquire (optional). :param timeout: (long), the maximum time in seconds to wait for the permit(s) (optional). :return: (bool), ``true`` if desired amount of permits was acquired, ``false`` otherwise. """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_try_acquire_codec, permits=permits, timeout=to_millis(timeout))
python
def try_acquire(self, permits=1, timeout=0): """ Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the value ``true``, reducing the number of available permits by the given amount. If there are insufficient permits and a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of following happens: * some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit, or * some other thread interrupts the current thread, or * the specified waiting time elapses. If there are insufficient permits and no timeout is provided, this method will return immediately with the value ``false`` and the number of available permits is unchanged. :param permits: (int), the number of permits to acquire (optional). :param timeout: (long), the maximum time in seconds to wait for the permit(s) (optional). :return: (bool), ``true`` if desired amount of permits was acquired, ``false`` otherwise. """ check_not_negative(permits, "Permits cannot be negative!") return self._encode_invoke(semaphore_try_acquire_codec, permits=permits, timeout=to_millis(timeout))
[ "def", "try_acquire", "(", "self", ",", "permits", "=", "1", ",", "timeout", "=", "0", ")", ":", "check_not_negative", "(", "permits", ",", "\"Permits cannot be negative!\"", ")", "return", "self", ".", "_encode_invoke", "(", "semaphore_try_acquire_codec", ",", ...
Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the value ``true``, reducing the number of available permits by the given amount. If there are insufficient permits and a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of following happens: * some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit, or * some other thread interrupts the current thread, or * the specified waiting time elapses. If there are insufficient permits and no timeout is provided, this method will return immediately with the value ``false`` and the number of available permits is unchanged. :param permits: (int), the number of permits to acquire (optional). :param timeout: (long), the maximum time in seconds to wait for the permit(s) (optional). :return: (bool), ``true`` if desired amount of permits was acquired, ``false`` otherwise.
[ "Tries", "to", "acquire", "one", "or", "the", "given", "number", "of", "permits", "if", "they", "are", "available", "and", "returns", "immediately", "with", "the", "value", "true", "reducing", "the", "number", "of", "available", "permits", "by", "the", "give...
3f6639443c23d6d036aa343f8e094f052250d2c1
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/semaphore.py#L100-L120
train
230,799