nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
ReactionMechanismGenerator/RMG-Py
2b7baf51febf27157def58fb3f6cee03fb6a684c
rmgpy/tools/uncertainty.py
python
KineticParameterUncertainty.get_uncertainty_factor
(self, source)
Retrieve the uncertainty factor f when the source of the reaction kinetics are given. This is equivalent to sqrt(3)/ln(10) * dlnk in a uniform uncertainty interval
Retrieve the uncertainty factor f when the source of the reaction kinetics are given. This is equivalent to sqrt(3)/ln(10) * dlnk in a uniform uncertainty interval
[ "Retrieve", "the", "uncertainty", "factor", "f", "when", "the", "source", "of", "the", "reaction", "kinetics", "are", "given", ".", "This", "is", "equivalent", "to", "sqrt", "(", "3", ")", "/", "ln", "(", "10", ")", "*", "dlnk", "in", "a", "uniform", "uncertainty", "interval" ]
def get_uncertainty_factor(self, source): """ Retrieve the uncertainty factor f when the source of the reaction kinetics are given. This is equivalent to sqrt(3)/ln(10) * dlnk in a uniform uncertainty interval """ dlnk = self.get_uncertainty_value(source) f = np.sqrt(3) / np.log(10) * dlnk
[ "def", "get_uncertainty_factor", "(", "self", ",", "source", ")", ":", "dlnk", "=", "self", ".", "get_uncertainty_value", "(", "source", ")", "f", "=", "np", ".", "sqrt", "(", "3", ")", "/", "np", ".", "log", "(", "10", ")", "*", "dlnk" ]
https://github.com/ReactionMechanismGenerator/RMG-Py/blob/2b7baf51febf27157def58fb3f6cee03fb6a684c/rmgpy/tools/uncertainty.py#L246-L253
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_tf_objects.py
python
TFBlenderbotForConditionalGeneration.call
(self, *args, **kwargs)
[]
def call(self, *args, **kwargs): requires_backends(self, ["tf"])
[ "def", "call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"tf\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_tf_objects.py#L568-L569
OpenZWave/python-openzwave
8be4c070294348f3fc268bc1d7ad2c535f352f5a
src-api/openzwave/command.py
python
ZWaveNodeThermostat.set_thermostat_mode
(self, value)
return False
The command 0x40 (COMMAND_CLASS_THERMOSTAT_MODE) of this node. Set MODE to value (using value). :param value: The mode : 'Off', 'Heat', 'Cool' :type value: String
The command 0x40 (COMMAND_CLASS_THERMOSTAT_MODE) of this node. Set MODE to value (using value).
[ "The", "command", "0x40", "(", "COMMAND_CLASS_THERMOSTAT_MODE", ")", "of", "this", "node", ".", "Set", "MODE", "to", "value", "(", "using", "value", ")", "." ]
def set_thermostat_mode(self, value): """ The command 0x40 (COMMAND_CLASS_THERMOSTAT_MODE) of this node. Set MODE to value (using value). :param value: The mode : 'Off', 'Heat', 'Cool' :type value: String """ logger.debug(u"set_thermostat_mode value:%s", value) for v in self.get_thermostats(): if self.values[v].command_class == 0x40 and self.values[v].label == 'Mode': self.values[v].data = value return True return False
[ "def", "set_thermostat_mode", "(", "self", ",", "value", ")", ":", "logger", ".", "debug", "(", "u\"set_thermostat_mode value:%s\"", ",", "value", ")", "for", "v", "in", "self", ".", "get_thermostats", "(", ")", ":", "if", "self", ".", "values", "[", "v", "]", ".", "command_class", "==", "0x40", "and", "self", ".", "values", "[", "v", "]", ".", "label", "==", "'Mode'", ":", "self", ".", "values", "[", "v", "]", ".", "data", "=", "value", "return", "True", "return", "False" ]
https://github.com/OpenZWave/python-openzwave/blob/8be4c070294348f3fc268bc1d7ad2c535f352f5a/src-api/openzwave/command.py#L795-L809
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/pychart/font.py
python
text_iterator.next
(self)
Get the next text segment. Return an 8-element array: (FONTNAME, SIZE, LINEHEIGHT, COLOR, H_ALIGN, V_ALIGN, ANGLE, STR.
Get the next text segment. Return an 8-element array: (FONTNAME, SIZE, LINEHEIGHT, COLOR, H_ALIGN, V_ALIGN, ANGLE, STR.
[ "Get", "the", "next", "text", "segment", ".", "Return", "an", "8", "-", "element", "array", ":", "(", "FONTNAME", "SIZE", "LINEHEIGHT", "COLOR", "H_ALIGN", "V_ALIGN", "ANGLE", "STR", "." ]
def next(self): "Get the next text segment. Return an 8-element array: (FONTNAME, SIZE, LINEHEIGHT, COLOR, H_ALIGN, V_ALIGN, ANGLE, STR." l = [] changed = 0 self.old_state = self.ts.copy() while self.i < len(self.str): if self.str[self.i] == '/': self.i = self.i+1 ch = self.str[self.i] self.i = self.i+1 self.old_state = self.ts.copy() if ch == '/' or ch == '{' or ch == '}': l.append(ch) elif _font_family_map.has_key(ch): self.ts.family = _font_family_map[ch] changed = 1 elif ch == 'F': # /F{font-family} if self.str[self.i] != '{': raise FontException('"{" must follow /F', self.str) self.i += 1 istart = self.i while self.str[self.i] != '}': self.i += 1 if self.i >= len(self.str): raise FontException('Expecting "/F{...}"', self.str) self.ts.family = self.str[istart:self.i] self.i += 1 changed = 1 elif ch in string.digits: self.i -= 1 self.ts.size = self.__parse_int() self.ts.line_height = self.ts.size changed = 1 elif ch == 'l': self.ts.line_height = self.__parse_int() changed = 1 elif ch == 'b': self.ts.modifiers.append('b') changed = 1 elif ch == 'i': self.ts.modifiers.append('i') changed = 1 elif ch == 'o': self.ts.modifiers.append('q') changed = 1 elif ch == 'c': self.ts.color = color.gray_scale(self.__parse_float()) elif ch == 'v': if self.str[self.i] not in 'BTM': raise FontException('Undefined escape sequence "/v%c"' % self.str[self.i], self.str) self.ts.valign = self.str[self.i] self.i += 1 changed = 1 elif ch == 'h': if self.str[self.i] not in 'LRC': raise FontException('Undefined escape sequence "/h%c"' % self.str[self.i], self.str) self.ts.halign = self.str[self.i] self.i += 1 changed = 1 elif ch == 'a': self.ts.angle = self.__parse_int() changed = 1 else: raise FontException('Undefined escape sequence: "/%c"' % ch, self.str) elif self.str[self.i] == '{': self.stack.append(self.ts.copy()) self.i += 1 elif self.str[self.i] == '}': if len(self.stack) == 0: raise FontError('Unmatched "}"', self.str) self.ts = self.stack[-1] del self.stack[-1] self.i += 1 changed = 1 else: l.append(self.str[self.i]) self.i += 1 if changed and len(l) > 0: return self.__return_state(self.old_state, ''.join(l)) else: # font change in the beginning of the sequence doesn't count. self.old_state = self.ts.copy() changed = 0 if len(l) > 0: return self.__return_state(self.old_state, ''.join(l)) else: return None
[ "def", "next", "(", "self", ")", ":", "l", "=", "[", "]", "changed", "=", "0", "self", ".", "old_state", "=", "self", ".", "ts", ".", "copy", "(", ")", "while", "self", ".", "i", "<", "len", "(", "self", ".", "str", ")", ":", "if", "self", ".", "str", "[", "self", ".", "i", "]", "==", "'/'", ":", "self", ".", "i", "=", "self", ".", "i", "+", "1", "ch", "=", "self", ".", "str", "[", "self", ".", "i", "]", "self", ".", "i", "=", "self", ".", "i", "+", "1", "self", ".", "old_state", "=", "self", ".", "ts", ".", "copy", "(", ")", "if", "ch", "==", "'/'", "or", "ch", "==", "'{'", "or", "ch", "==", "'}'", ":", "l", ".", "append", "(", "ch", ")", "elif", "_font_family_map", ".", "has_key", "(", "ch", ")", ":", "self", ".", "ts", ".", "family", "=", "_font_family_map", "[", "ch", "]", "changed", "=", "1", "elif", "ch", "==", "'F'", ":", "# /F{font-family}", "if", "self", ".", "str", "[", "self", ".", "i", "]", "!=", "'{'", ":", "raise", "FontException", "(", "'\"{\" must follow /F'", ",", "self", ".", "str", ")", "self", ".", "i", "+=", "1", "istart", "=", "self", ".", "i", "while", "self", ".", "str", "[", "self", ".", "i", "]", "!=", "'}'", ":", "self", ".", "i", "+=", "1", "if", "self", ".", "i", ">=", "len", "(", "self", ".", "str", ")", ":", "raise", "FontException", "(", "'Expecting \"/F{...}\"'", ",", "self", ".", "str", ")", "self", ".", "ts", ".", "family", "=", "self", ".", "str", "[", "istart", ":", "self", ".", "i", "]", "self", ".", "i", "+=", "1", "changed", "=", "1", "elif", "ch", "in", "string", ".", "digits", ":", "self", ".", "i", "-=", "1", "self", ".", "ts", ".", "size", "=", "self", ".", "__parse_int", "(", ")", "self", ".", "ts", ".", "line_height", "=", "self", ".", "ts", ".", "size", "changed", "=", "1", "elif", "ch", "==", "'l'", ":", "self", ".", "ts", ".", "line_height", "=", "self", ".", "__parse_int", "(", ")", "changed", "=", "1", "elif", "ch", "==", "'b'", ":", "self", ".", "ts", ".", "modifiers", ".", "append", "(", "'b'", ")", "changed", "=", "1", "elif", "ch", "==", "'i'", ":", "self", ".", "ts", ".", "modifiers", ".", "append", "(", "'i'", ")", "changed", "=", "1", "elif", "ch", "==", "'o'", ":", "self", ".", "ts", ".", "modifiers", ".", "append", "(", "'q'", ")", "changed", "=", "1", "elif", "ch", "==", "'c'", ":", "self", ".", "ts", ".", "color", "=", "color", ".", "gray_scale", "(", "self", ".", "__parse_float", "(", ")", ")", "elif", "ch", "==", "'v'", ":", "if", "self", ".", "str", "[", "self", ".", "i", "]", "not", "in", "'BTM'", ":", "raise", "FontException", "(", "'Undefined escape sequence \"/v%c\"'", "%", "self", ".", "str", "[", "self", ".", "i", "]", ",", "self", ".", "str", ")", "self", ".", "ts", ".", "valign", "=", "self", ".", "str", "[", "self", ".", "i", "]", "self", ".", "i", "+=", "1", "changed", "=", "1", "elif", "ch", "==", "'h'", ":", "if", "self", ".", "str", "[", "self", ".", "i", "]", "not", "in", "'LRC'", ":", "raise", "FontException", "(", "'Undefined escape sequence \"/h%c\"'", "%", "self", ".", "str", "[", "self", ".", "i", "]", ",", "self", ".", "str", ")", "self", ".", "ts", ".", "halign", "=", "self", ".", "str", "[", "self", ".", "i", "]", "self", ".", "i", "+=", "1", "changed", "=", "1", "elif", "ch", "==", "'a'", ":", "self", ".", "ts", ".", "angle", "=", "self", ".", "__parse_int", "(", ")", "changed", "=", "1", "else", ":", "raise", "FontException", "(", "'Undefined escape sequence: \"/%c\"'", "%", "ch", ",", "self", ".", "str", ")", "elif", "self", ".", "str", "[", "self", ".", "i", "]", "==", "'{'", ":", "self", ".", "stack", ".", "append", "(", "self", ".", "ts", ".", "copy", "(", ")", ")", "self", ".", "i", "+=", "1", "elif", "self", ".", "str", "[", "self", ".", "i", "]", "==", "'}'", ":", "if", "len", "(", "self", ".", "stack", ")", "==", "0", ":", "raise", "FontError", "(", "'Unmatched \"}\"'", ",", "self", ".", "str", ")", "self", ".", "ts", "=", "self", ".", "stack", "[", "-", "1", "]", "del", "self", ".", "stack", "[", "-", "1", "]", "self", ".", "i", "+=", "1", "changed", "=", "1", "else", ":", "l", ".", "append", "(", "self", ".", "str", "[", "self", ".", "i", "]", ")", "self", ".", "i", "+=", "1", "if", "changed", "and", "len", "(", "l", ")", ">", "0", ":", "return", "self", ".", "__return_state", "(", "self", ".", "old_state", ",", "''", ".", "join", "(", "l", ")", ")", "else", ":", "# font change in the beginning of the sequence doesn't count.", "self", ".", "old_state", "=", "self", ".", "ts", ".", "copy", "(", ")", "changed", "=", "0", "if", "len", "(", "l", ")", ">", "0", ":", "return", "self", ".", "__return_state", "(", "self", ".", "old_state", ",", "''", ".", "join", "(", "l", ")", ")", "else", ":", "return", "None" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/pychart/font.py#L262-L355
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/fallback_lib_py352/asyncio/selector_events.py
python
BaseSelectorEventLoop.sock_recv
(self, sock, n)
return await fut
Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by nbytes.
Receive data from the socket.
[ "Receive", "data", "from", "the", "socket", "." ]
async def sock_recv(self, sock, n): """Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by nbytes. """ if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") fut = self.create_future() self._sock_recv(fut, None, sock, n) return await fut
[ "async", "def", "sock_recv", "(", "self", ",", "sock", ",", "n", ")", ":", "if", "self", ".", "_debug", "and", "sock", ".", "gettimeout", "(", ")", "!=", "0", ":", "raise", "ValueError", "(", "\"the socket must be non-blocking\"", ")", "fut", "=", "self", ".", "create_future", "(", ")", "self", ".", "_sock_recv", "(", "fut", ",", "None", ",", "sock", ",", "n", ")", "return", "await", "fut" ]
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/fallback_lib_py352/asyncio/selector_events.py#L341-L352
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/clients/polling/telegram/config.py
python
TelegramConfiguration.to_yaml
(self, data, defaults=True)
[]
def to_yaml(self, data, defaults=True): if defaults is True: data['unknown_command'] = "Sorry, that is not a command I have been taught yet!" data['unknown_command_srai'] = 'YTELEGRAM_UNKNOWN_COMMAND' else: data['unknown_command'] = self._unknown_command data['unknown_command_srai'] = self._unknown_command_srai super(TelegramConfiguration, self).to_yaml(data, defaults)
[ "def", "to_yaml", "(", "self", ",", "data", ",", "defaults", "=", "True", ")", ":", "if", "defaults", "is", "True", ":", "data", "[", "'unknown_command'", "]", "=", "\"Sorry, that is not a command I have been taught yet!\"", "data", "[", "'unknown_command_srai'", "]", "=", "'YTELEGRAM_UNKNOWN_COMMAND'", "else", ":", "data", "[", "'unknown_command'", "]", "=", "self", ".", "_unknown_command", "data", "[", "'unknown_command_srai'", "]", "=", "self", ".", "_unknown_command_srai", "super", "(", "TelegramConfiguration", ",", "self", ")", ".", "to_yaml", "(", "data", ",", "defaults", ")" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/clients/polling/telegram/config.py#L46-L54
python273/vk_api
1ef82594baabc80802ef4792aceee9180ae3e9c9
vk_api/vk_api.py
python
VkApi._pass_twofactor
(self, auth_response)
Двухфакторная аутентификация :param auth_response: страница с приглашением к аутентификации
Двухфакторная аутентификация
[ "Двухфакторная", "аутентификация" ]
def _pass_twofactor(self, auth_response): """ Двухфакторная аутентификация :param auth_response: страница с приглашением к аутентификации """ auth_hash = search_re(RE_AUTH_HASH, auth_response.text) if not auth_hash: raise TwoFactorError(get_unknown_exc_str('2FA; no hash')) code, remember_device = self.error_handlers[TWOFACTOR_CODE]() values = { 'al': '1', 'code': code, 'hash': auth_hash, 'remember': int(remember_device), } response = self.http.post( 'https://vk.com/al_login.php?act=a_authcheck_code', values ) data = json.loads(response.text.lstrip('<!--')) status = data['payload'][0] if status == '4': # OK path = json.loads(data['payload'][1][0]) return self.http.get(path) elif status in [0, '8']: # Incorrect code return self._pass_twofactor(auth_response) elif status == '2': raise TwoFactorError('Recaptcha required') raise TwoFactorError(get_unknown_exc_str('2FA; unknown status'))
[ "def", "_pass_twofactor", "(", "self", ",", "auth_response", ")", ":", "auth_hash", "=", "search_re", "(", "RE_AUTH_HASH", ",", "auth_response", ".", "text", ")", "if", "not", "auth_hash", ":", "raise", "TwoFactorError", "(", "get_unknown_exc_str", "(", "'2FA; no hash'", ")", ")", "code", ",", "remember_device", "=", "self", ".", "error_handlers", "[", "TWOFACTOR_CODE", "]", "(", ")", "values", "=", "{", "'al'", ":", "'1'", ",", "'code'", ":", "code", ",", "'hash'", ":", "auth_hash", ",", "'remember'", ":", "int", "(", "remember_device", ")", ",", "}", "response", "=", "self", ".", "http", ".", "post", "(", "'https://vk.com/al_login.php?act=a_authcheck_code'", ",", "values", ")", "data", "=", "json", ".", "loads", "(", "response", ".", "text", ".", "lstrip", "(", "'<!--'", ")", ")", "status", "=", "data", "[", "'payload'", "]", "[", "0", "]", "if", "status", "==", "'4'", ":", "# OK", "path", "=", "json", ".", "loads", "(", "data", "[", "'payload'", "]", "[", "1", "]", "[", "0", "]", ")", "return", "self", ".", "http", ".", "get", "(", "path", ")", "elif", "status", "in", "[", "0", ",", "'8'", "]", ":", "# Incorrect code", "return", "self", ".", "_pass_twofactor", "(", "auth_response", ")", "elif", "status", "==", "'2'", ":", "raise", "TwoFactorError", "(", "'Recaptcha required'", ")", "raise", "TwoFactorError", "(", "get_unknown_exc_str", "(", "'2FA; unknown status'", ")", ")" ]
https://github.com/python273/vk_api/blob/1ef82594baabc80802ef4792aceee9180ae3e9c9/vk_api/vk_api.py#L337-L374
QuarkChain/pyquarkchain
af1dd06a50d918aaf45569d9b0f54f5ecceb6afe
quarkchain/p2p/poc/trinity_disc_network.py
python
Network.run_apps
(self)
run bootstrap node (first process) first, sleep for 3 seconds
run bootstrap node (first process) first, sleep for 3 seconds
[ "run", "bootstrap", "node", "(", "first", "process", ")", "first", "sleep", "for", "3", "seconds" ]
async def run_apps(self): """ run bootstrap node (first process) first, sleep for 3 seconds """ bootnode = "enode://c571e0db93d17cc405cb57640826b70588a6a28785f38b21be471c609ca12fcb06cb306ac44872908f5bed99046031a5af82072d484e3ef9029560c1707193a0@127.0.0.1:{}".format( self.port_start ) s = await run_app( bootnode=bootnode, listen_host="127.0.0.1", listen_port=self.port_start, max_peers=self.max_peers, privkey="31552f186bf90908ce386fb547dd0410bf443309125cc43fd0ffd642959bf6d9", ) prefix = "APP_{}".format(0) asyncio.ensure_future(print_output(prefix, s.stdout)) self.procs.append((prefix, s)) await asyncio.sleep(3) for id in range(1, self.num_apps): s = await run_app( bootnode=bootnode, listen_host="127.0.0.1", listen_port=self.port_start + id, max_peers=self.max_peers, privkey="", ) prefix = "APP_{}".format(id) asyncio.ensure_future(print_output(prefix, s.stdout)) self.procs.append((prefix, s)) await asyncio.sleep(0.5)
[ "async", "def", "run_apps", "(", "self", ")", ":", "bootnode", "=", "\"enode://c571e0db93d17cc405cb57640826b70588a6a28785f38b21be471c609ca12fcb06cb306ac44872908f5bed99046031a5af82072d484e3ef9029560c1707193a0@127.0.0.1:{}\"", ".", "format", "(", "self", ".", "port_start", ")", "s", "=", "await", "run_app", "(", "bootnode", "=", "bootnode", ",", "listen_host", "=", "\"127.0.0.1\"", ",", "listen_port", "=", "self", ".", "port_start", ",", "max_peers", "=", "self", ".", "max_peers", ",", "privkey", "=", "\"31552f186bf90908ce386fb547dd0410bf443309125cc43fd0ffd642959bf6d9\"", ",", ")", "prefix", "=", "\"APP_{}\"", ".", "format", "(", "0", ")", "asyncio", ".", "ensure_future", "(", "print_output", "(", "prefix", ",", "s", ".", "stdout", ")", ")", "self", ".", "procs", ".", "append", "(", "(", "prefix", ",", "s", ")", ")", "await", "asyncio", ".", "sleep", "(", "3", ")", "for", "id", "in", "range", "(", "1", ",", "self", ".", "num_apps", ")", ":", "s", "=", "await", "run_app", "(", "bootnode", "=", "bootnode", ",", "listen_host", "=", "\"127.0.0.1\"", ",", "listen_port", "=", "self", ".", "port_start", "+", "id", ",", "max_peers", "=", "self", ".", "max_peers", ",", "privkey", "=", "\"\"", ",", ")", "prefix", "=", "\"APP_{}\"", ".", "format", "(", "id", ")", "asyncio", ".", "ensure_future", "(", "print_output", "(", "prefix", ",", "s", ".", "stdout", ")", ")", "self", ".", "procs", ".", "append", "(", "(", "prefix", ",", "s", ")", ")", "await", "asyncio", ".", "sleep", "(", "0.5", ")" ]
https://github.com/QuarkChain/pyquarkchain/blob/af1dd06a50d918aaf45569d9b0f54f5ecceb6afe/quarkchain/p2p/poc/trinity_disc_network.py#L55-L84
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/cool.py
python
getCraftedTextFromText
(gcodeText, repository=None)
return CoolSkein().getCraftedGcode(gcodeText, repository)
Cool a gcode linear move text.
Cool a gcode linear move text.
[ "Cool", "a", "gcode", "linear", "move", "text", "." ]
def getCraftedTextFromText(gcodeText, repository=None): 'Cool a gcode linear move text.' if gcodec.isProcedureDoneOrFileIsEmpty(gcodeText, 'cool'): return gcodeText if repository == None: repository = settings.getReadRepository(CoolRepository()) if not repository.activateCool.value: return gcodeText return CoolSkein().getCraftedGcode(gcodeText, repository)
[ "def", "getCraftedTextFromText", "(", "gcodeText", ",", "repository", "=", "None", ")", ":", "if", "gcodec", ".", "isProcedureDoneOrFileIsEmpty", "(", "gcodeText", ",", "'cool'", ")", ":", "return", "gcodeText", "if", "repository", "==", "None", ":", "repository", "=", "settings", ".", "getReadRepository", "(", "CoolRepository", "(", ")", ")", "if", "not", "repository", ".", "activateCool", ".", "value", ":", "return", "gcodeText", "return", "CoolSkein", "(", ")", ".", "getCraftedGcode", "(", "gcodeText", ",", "repository", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/cool.py#L118-L126
tipam/pi3d
1f1c822dc3ac58344ad2d5468978d62e51710df4
pi3d/shape/Triangle.py
python
Triangle.__init__
(self, camera=None, light=None, name="", corners=((-0.5, -0.28868), (0.0, 0.57735), (0.5, -0.28868)), x=0.0, y=0.0, z=0.0, sx=1.0, sy=1.0, sz=1.0, rx=0.0, ry=0.0, rz=0.0, cx=0.0, cy=0.0, cz=0.0)
Uses standard constructor for Shape with ability to position corners. The corners must be arranged clockwise (for the Triangle to face -z direction) Keyword argument: *corners* A tuple of three (xy) tuples defining the corners
Uses standard constructor for Shape with ability to position corners. The corners must be arranged clockwise (for the Triangle to face -z direction)
[ "Uses", "standard", "constructor", "for", "Shape", "with", "ability", "to", "position", "corners", ".", "The", "corners", "must", "be", "arranged", "clockwise", "(", "for", "the", "Triangle", "to", "face", "-", "z", "direction", ")" ]
def __init__(self, camera=None, light=None, name="", corners=((-0.5, -0.28868), (0.0, 0.57735), (0.5, -0.28868)), x=0.0, y=0.0, z=0.0, sx=1.0, sy=1.0, sz=1.0, rx=0.0, ry=0.0, rz=0.0, cx=0.0, cy=0.0, cz=0.0): """Uses standard constructor for Shape with ability to position corners. The corners must be arranged clockwise (for the Triangle to face -z direction) Keyword argument: *corners* A tuple of three (xy) tuples defining the corners """ super(Triangle, self).__init__(camera, light, name, x, y, z, rx, ry, rz, sx, sy, sz, cx, cy, cz) c = corners # alias for convenience verts = ((c[0][0], c[0][1], 0.0), (c[1][0], c[1][1], 0.0), (c[2][0], c[2][1], 0.0)) norms = ((0, 0, -1), (0, 0, -1), (0, 0, -1)) maxx = max(v[0] for v in corners) # u,v to match vertex locations minx = min(v[0] for v in corners) xscale = 1.0 / (maxx - minx) maxy = max(v[1] for v in corners) miny = min(v[1] for v in corners) yscale = 1.0 / (maxy - miny) texcoords = [((v[0] - minx) * xscale, 1.0 - (v[1] - miny) * yscale) for v in verts] inds = ((0, 1, 2), ) #python quirk: comma for tuple with only one val self.buf = [Buffer(self, verts, texcoords, inds, norms)]
[ "def", "__init__", "(", "self", ",", "camera", "=", "None", ",", "light", "=", "None", ",", "name", "=", "\"\"", ",", "corners", "=", "(", "(", "-", "0.5", ",", "-", "0.28868", ")", ",", "(", "0.0", ",", "0.57735", ")", ",", "(", "0.5", ",", "-", "0.28868", ")", ")", ",", "x", "=", "0.0", ",", "y", "=", "0.0", ",", "z", "=", "0.0", ",", "sx", "=", "1.0", ",", "sy", "=", "1.0", ",", "sz", "=", "1.0", ",", "rx", "=", "0.0", ",", "ry", "=", "0.0", ",", "rz", "=", "0.0", ",", "cx", "=", "0.0", ",", "cy", "=", "0.0", ",", "cz", "=", "0.0", ")", ":", "super", "(", "Triangle", ",", "self", ")", ".", "__init__", "(", "camera", ",", "light", ",", "name", ",", "x", ",", "y", ",", "z", ",", "rx", ",", "ry", ",", "rz", ",", "sx", ",", "sy", ",", "sz", ",", "cx", ",", "cy", ",", "cz", ")", "c", "=", "corners", "# alias for convenience", "verts", "=", "(", "(", "c", "[", "0", "]", "[", "0", "]", ",", "c", "[", "0", "]", "[", "1", "]", ",", "0.0", ")", ",", "(", "c", "[", "1", "]", "[", "0", "]", ",", "c", "[", "1", "]", "[", "1", "]", ",", "0.0", ")", ",", "(", "c", "[", "2", "]", "[", "0", "]", ",", "c", "[", "2", "]", "[", "1", "]", ",", "0.0", ")", ")", "norms", "=", "(", "(", "0", ",", "0", ",", "-", "1", ")", ",", "(", "0", ",", "0", ",", "-", "1", ")", ",", "(", "0", ",", "0", ",", "-", "1", ")", ")", "maxx", "=", "max", "(", "v", "[", "0", "]", "for", "v", "in", "corners", ")", "# u,v to match vertex locations", "minx", "=", "min", "(", "v", "[", "0", "]", "for", "v", "in", "corners", ")", "xscale", "=", "1.0", "/", "(", "maxx", "-", "minx", ")", "maxy", "=", "max", "(", "v", "[", "1", "]", "for", "v", "in", "corners", ")", "miny", "=", "min", "(", "v", "[", "1", "]", "for", "v", "in", "corners", ")", "yscale", "=", "1.0", "/", "(", "maxy", "-", "miny", ")", "texcoords", "=", "[", "(", "(", "v", "[", "0", "]", "-", "minx", ")", "*", "xscale", ",", "1.0", "-", "(", "v", "[", "1", "]", "-", "miny", ")", "*", "yscale", ")", "for", "v", "in", "verts", "]", "inds", "=", "(", "(", "0", ",", "1", ",", "2", ")", ",", ")", "#python quirk: comma for tuple with only one val", "self", ".", "buf", "=", "[", "Buffer", "(", "self", ",", "verts", ",", "texcoords", ",", "inds", ",", "norms", ")", "]" ]
https://github.com/tipam/pi3d/blob/1f1c822dc3ac58344ad2d5468978d62e51710df4/pi3d/shape/Triangle.py#L8-L36
jfzhang95/pytorch-video-recognition
ca37de9f69a961f22a821c157e9ccf47a601904d
dataloaders/dataset.py
python
VideoDataset.to_tensor
(self, buffer)
return buffer.transpose((3, 0, 1, 2))
[]
def to_tensor(self, buffer): return buffer.transpose((3, 0, 1, 2))
[ "def", "to_tensor", "(", "self", ",", "buffer", ")", ":", "return", "buffer", ".", "transpose", "(", "(", "3", ",", "0", ",", "1", ",", "2", ")", ")" ]
https://github.com/jfzhang95/pytorch-video-recognition/blob/ca37de9f69a961f22a821c157e9ccf47a601904d/dataloaders/dataset.py#L211-L212
etal/cnvkit
09208296f95685bc7a34660d440a83aaa14964b8
cnvlib/scatter.py
python
select_range_genes
(cnarr, segments, variants, show_range, show_gene, window_width)
return sel_probes, sel_segs, sel_snvs, window_coords, gene_ranges, chrom
Determine which datapoints to show based on the given options. Behaviors:: start/end show_gene + + given region + genes; err if any gene outside it - + window +/- around genes + - given region, highlighting any genes within it - - whole chromosome, no genes If `show_range` is a chromosome name only, no start/end positions, then the whole chromosome will be shown. If region start/end coordinates are given and `show_gene` is '' or ',' (or all commas, etc.), then instead of highlighting all genes in the selection, no genes will be highlighted.
Determine which datapoints to show based on the given options.
[ "Determine", "which", "datapoints", "to", "show", "based", "on", "the", "given", "options", "." ]
def select_range_genes(cnarr, segments, variants, show_range, show_gene, window_width): """Determine which datapoints to show based on the given options. Behaviors:: start/end show_gene + + given region + genes; err if any gene outside it - + window +/- around genes + - given region, highlighting any genes within it - - whole chromosome, no genes If `show_range` is a chromosome name only, no start/end positions, then the whole chromosome will be shown. If region start/end coordinates are given and `show_gene` is '' or ',' (or all commas, etc.), then instead of highlighting all genes in the selection, no genes will be highlighted. """ chrom, start, end = unpack_range(show_range) if start is None and end is None: # Either the specified range is only chrom, no start-end, or gene names # were given window_coords = () else: # Viewing region coordinates were specified -- take them as given # Fill in open-ended ranges' endpoints if start is None: start = 0 elif start < 0: start = 0 if not end: # Default selection endpoint to the maximum chromosome position end = (cnarr or segments or variants ).filter(chromosome=chrom).end.iat[-1] if end <= start: raise ValueError("Coordinate range {}:{}-{} (from {}) has size <= 0" .format(chrom, start, end, show_range)) window_coords = (start, end) gene_ranges = [] if show_gene is None: if window_coords: if cnarr: # Highlight all genes within the given range gene_ranges = plots.gene_coords_by_range(cnarr, chrom, start, end)[chrom] if not gene_ranges and (end - start) < 10 * window_width: # No genes in the selected region, so if the selection is small # (i.e. <80% of the displayed window, <10x window padding), # highlight the selected region itself. # (To prevent this, use show_gene='' or window_width=0) logging.info("No genes found in selection; will highlight the " "selected region itself instead") gene_ranges = [(start, end, "Selection")] window_coords = (max(0, start - window_width), end + window_width) else: gene_names = filter(None, show_gene.split(',')) if gene_names: # Scan for probes matching the specified gene(s) gene_coords = plots.gene_coords_by_name(cnarr or segments, gene_names) if len(gene_coords) > 1: raise ValueError("Genes %s are split across chromosomes %s" % (show_gene, list(gene_coords.keys()))) g_chrom, gene_ranges = gene_coords.popitem() if chrom: # Confirm that the selected chromosomes match core.assert_equal("Chromosome also selected by region (-c) " "does not match", **{"chromosome": chrom, "gene(s)": g_chrom}) else: chrom = g_chrom gene_ranges.sort() if window_coords: # Verify all genes fit in the given window for gene_start, gene_end, gene_name in gene_ranges: if not (start <= gene_start and gene_end <= end): raise ValueError("Selected gene %s (%s:%d-%d) " "is outside specified region %s" % (gene_name, chrom, gene_start, gene_end, show_range)) elif not show_range: # Set the display window to the selected genes +/- a margin window_coords = (max(0, gene_ranges[0][0] - window_width), gene_ranges[-1][1] + window_width) # Prune plotted elements to the selected region sel_probes = (cnarr.in_range(chrom, *window_coords) if cnarr else CNA([])) sel_segs = (segments.in_range(chrom, *window_coords, mode='trim') if segments else CNA([])) sel_snvs = (variants.in_range(chrom, *window_coords) if variants else None) logging.info("Showing %d probes and %d selected genes in region %s", len(sel_probes), len(gene_ranges), (chrom + ":%d-%d" % window_coords if window_coords else chrom)) return sel_probes, sel_segs, sel_snvs, window_coords, gene_ranges, chrom
[ "def", "select_range_genes", "(", "cnarr", ",", "segments", ",", "variants", ",", "show_range", ",", "show_gene", ",", "window_width", ")", ":", "chrom", ",", "start", ",", "end", "=", "unpack_range", "(", "show_range", ")", "if", "start", "is", "None", "and", "end", "is", "None", ":", "# Either the specified range is only chrom, no start-end, or gene names", "# were given", "window_coords", "=", "(", ")", "else", ":", "# Viewing region coordinates were specified -- take them as given", "# Fill in open-ended ranges' endpoints", "if", "start", "is", "None", ":", "start", "=", "0", "elif", "start", "<", "0", ":", "start", "=", "0", "if", "not", "end", ":", "# Default selection endpoint to the maximum chromosome position", "end", "=", "(", "cnarr", "or", "segments", "or", "variants", ")", ".", "filter", "(", "chromosome", "=", "chrom", ")", ".", "end", ".", "iat", "[", "-", "1", "]", "if", "end", "<=", "start", ":", "raise", "ValueError", "(", "\"Coordinate range {}:{}-{} (from {}) has size <= 0\"", ".", "format", "(", "chrom", ",", "start", ",", "end", ",", "show_range", ")", ")", "window_coords", "=", "(", "start", ",", "end", ")", "gene_ranges", "=", "[", "]", "if", "show_gene", "is", "None", ":", "if", "window_coords", ":", "if", "cnarr", ":", "# Highlight all genes within the given range", "gene_ranges", "=", "plots", ".", "gene_coords_by_range", "(", "cnarr", ",", "chrom", ",", "start", ",", "end", ")", "[", "chrom", "]", "if", "not", "gene_ranges", "and", "(", "end", "-", "start", ")", "<", "10", "*", "window_width", ":", "# No genes in the selected region, so if the selection is small", "# (i.e. <80% of the displayed window, <10x window padding),", "# highlight the selected region itself.", "# (To prevent this, use show_gene='' or window_width=0)", "logging", ".", "info", "(", "\"No genes found in selection; will highlight the \"", "\"selected region itself instead\"", ")", "gene_ranges", "=", "[", "(", "start", ",", "end", ",", "\"Selection\"", ")", "]", "window_coords", "=", "(", "max", "(", "0", ",", "start", "-", "window_width", ")", ",", "end", "+", "window_width", ")", "else", ":", "gene_names", "=", "filter", "(", "None", ",", "show_gene", ".", "split", "(", "','", ")", ")", "if", "gene_names", ":", "# Scan for probes matching the specified gene(s)", "gene_coords", "=", "plots", ".", "gene_coords_by_name", "(", "cnarr", "or", "segments", ",", "gene_names", ")", "if", "len", "(", "gene_coords", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Genes %s are split across chromosomes %s\"", "%", "(", "show_gene", ",", "list", "(", "gene_coords", ".", "keys", "(", ")", ")", ")", ")", "g_chrom", ",", "gene_ranges", "=", "gene_coords", ".", "popitem", "(", ")", "if", "chrom", ":", "# Confirm that the selected chromosomes match", "core", ".", "assert_equal", "(", "\"Chromosome also selected by region (-c) \"", "\"does not match\"", ",", "*", "*", "{", "\"chromosome\"", ":", "chrom", ",", "\"gene(s)\"", ":", "g_chrom", "}", ")", "else", ":", "chrom", "=", "g_chrom", "gene_ranges", ".", "sort", "(", ")", "if", "window_coords", ":", "# Verify all genes fit in the given window", "for", "gene_start", ",", "gene_end", ",", "gene_name", "in", "gene_ranges", ":", "if", "not", "(", "start", "<=", "gene_start", "and", "gene_end", "<=", "end", ")", ":", "raise", "ValueError", "(", "\"Selected gene %s (%s:%d-%d) \"", "\"is outside specified region %s\"", "%", "(", "gene_name", ",", "chrom", ",", "gene_start", ",", "gene_end", ",", "show_range", ")", ")", "elif", "not", "show_range", ":", "# Set the display window to the selected genes +/- a margin", "window_coords", "=", "(", "max", "(", "0", ",", "gene_ranges", "[", "0", "]", "[", "0", "]", "-", "window_width", ")", ",", "gene_ranges", "[", "-", "1", "]", "[", "1", "]", "+", "window_width", ")", "# Prune plotted elements to the selected region", "sel_probes", "=", "(", "cnarr", ".", "in_range", "(", "chrom", ",", "*", "window_coords", ")", "if", "cnarr", "else", "CNA", "(", "[", "]", ")", ")", "sel_segs", "=", "(", "segments", ".", "in_range", "(", "chrom", ",", "*", "window_coords", ",", "mode", "=", "'trim'", ")", "if", "segments", "else", "CNA", "(", "[", "]", ")", ")", "sel_snvs", "=", "(", "variants", ".", "in_range", "(", "chrom", ",", "*", "window_coords", ")", "if", "variants", "else", "None", ")", "logging", ".", "info", "(", "\"Showing %d probes and %d selected genes in region %s\"", ",", "len", "(", "sel_probes", ")", ",", "len", "(", "gene_ranges", ")", ",", "(", "chrom", "+", "\":%d-%d\"", "%", "window_coords", "if", "window_coords", "else", "chrom", ")", ")", "return", "sel_probes", ",", "sel_segs", ",", "sel_snvs", ",", "window_coords", ",", "gene_ranges", ",", "chrom" ]
https://github.com/etal/cnvkit/blob/09208296f95685bc7a34660d440a83aaa14964b8/cnvlib/scatter.py#L248-L349
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/apps_v1beta1_scale_spec.py
python
AppsV1beta1ScaleSpec.replicas
(self)
return self._replicas
Gets the replicas of this AppsV1beta1ScaleSpec. desired number of instances for the scaled object. :return: The replicas of this AppsV1beta1ScaleSpec. :rtype: int
Gets the replicas of this AppsV1beta1ScaleSpec. desired number of instances for the scaled object.
[ "Gets", "the", "replicas", "of", "this", "AppsV1beta1ScaleSpec", ".", "desired", "number", "of", "instances", "for", "the", "scaled", "object", "." ]
def replicas(self): """ Gets the replicas of this AppsV1beta1ScaleSpec. desired number of instances for the scaled object. :return: The replicas of this AppsV1beta1ScaleSpec. :rtype: int """ return self._replicas
[ "def", "replicas", "(", "self", ")", ":", "return", "self", ".", "_replicas" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/apps_v1beta1_scale_spec.py#L44-L52
GalSim-developers/GalSim
a05d4ec3b8d8574f99d3b0606ad882cbba53f345
docs/_build/html/_downloads/5a3fd734fc69032ea0359196db84be9c/des_wcs.py
python
DES_LocalWCSBuilder.buildWCS
(self, config, base, logger)
return local_wcs
Build a local WCS from the given location in a DES focal plane. This function is used in conjunction with the des_wcs input field, which loads all the files at the start. By default, it will pick a random chipnum and image position, but these can be optionally specified.
Build a local WCS from the given location in a DES focal plane.
[ "Build", "a", "local", "WCS", "from", "the", "given", "location", "in", "a", "DES", "focal", "plane", "." ]
def buildWCS(self, config, base, logger): """Build a local WCS from the given location in a DES focal plane. This function is used in conjunction with the des_wcs input field, which loads all the files at the start. By default, it will pick a random chipnum and image position, but these can be optionally specified. """ opt = { "chipnum" : int, # Which chip to use: 1-62. Default is to pick a random chip. "image_pos" : galsim.PositionD, # The position in the chip. Default is random. } params, safe = galsim.config.GetAllParams(config, base, opt=opt) rng = base['rng'] ud = galsim.UniformDeviate(rng) # Will give float values between 0 and 1. # Get the input des_wcs object. The last parameter is just used for error reporting, and # should be the name of the current type being processed. des_wcs = galsim.config.GetInputObj('des_wcs', config, base, 'DES_LocalWCS') if 'chipnum' in params: chipnum = params['chipnum'] else: chipnum=get_random_chipnum(ud, des_wcs.get_bad_ccds()) full_wcs = des_wcs.get_chip_wcs(chipnum) # Determine where in the image we will get the local WCS if 'image_pos' in params: image_pos = params['image_pos'] else: x = ud() * 2048. + 0.5 # The pixel centers go from 1-2048, so edges are 0.5-2048.5 y = ud() * 4096. + 0.5 image_pos = galsim.PositionD(x,y) # Finally, return the local wcs at this location. local_wcs = full_wcs.local(image_pos) return local_wcs
[ "def", "buildWCS", "(", "self", ",", "config", ",", "base", ",", "logger", ")", ":", "opt", "=", "{", "\"chipnum\"", ":", "int", ",", "# Which chip to use: 1-62. Default is to pick a random chip.", "\"image_pos\"", ":", "galsim", ".", "PositionD", ",", "# The position in the chip. Default is random.", "}", "params", ",", "safe", "=", "galsim", ".", "config", ".", "GetAllParams", "(", "config", ",", "base", ",", "opt", "=", "opt", ")", "rng", "=", "base", "[", "'rng'", "]", "ud", "=", "galsim", ".", "UniformDeviate", "(", "rng", ")", "# Will give float values between 0 and 1.", "# Get the input des_wcs object. The last parameter is just used for error reporting, and", "# should be the name of the current type being processed.", "des_wcs", "=", "galsim", ".", "config", ".", "GetInputObj", "(", "'des_wcs'", ",", "config", ",", "base", ",", "'DES_LocalWCS'", ")", "if", "'chipnum'", "in", "params", ":", "chipnum", "=", "params", "[", "'chipnum'", "]", "else", ":", "chipnum", "=", "get_random_chipnum", "(", "ud", ",", "des_wcs", ".", "get_bad_ccds", "(", ")", ")", "full_wcs", "=", "des_wcs", ".", "get_chip_wcs", "(", "chipnum", ")", "# Determine where in the image we will get the local WCS", "if", "'image_pos'", "in", "params", ":", "image_pos", "=", "params", "[", "'image_pos'", "]", "else", ":", "x", "=", "ud", "(", ")", "*", "2048.", "+", "0.5", "# The pixel centers go from 1-2048, so edges are 0.5-2048.5", "y", "=", "ud", "(", ")", "*", "4096.", "+", "0.5", "image_pos", "=", "galsim", ".", "PositionD", "(", "x", ",", "y", ")", "# Finally, return the local wcs at this location.", "local_wcs", "=", "full_wcs", ".", "local", "(", "image_pos", ")", "return", "local_wcs" ]
https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/docs/_build/html/_downloads/5a3fd734fc69032ea0359196db84be9c/des_wcs.py#L147-L186
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
var/spack/repos/builtin/packages/aocl-sparse/package.py
python
AoclSparse.build_directory
(self)
return build_directory
Returns the directory to use when building the package :return: directory where to build the package
Returns the directory to use when building the package
[ "Returns", "the", "directory", "to", "use", "when", "building", "the", "package" ]
def build_directory(self): """Returns the directory to use when building the package :return: directory where to build the package """ build_directory = self.stage.source_path if self.spec.variants['build_type'].value == 'Debug': build_directory = join_path(build_directory, 'build', 'debug') else: build_directory = join_path(build_directory, 'build', 'release') return build_directory
[ "def", "build_directory", "(", "self", ")", ":", "build_directory", "=", "self", ".", "stage", ".", "source_path", "if", "self", ".", "spec", ".", "variants", "[", "'build_type'", "]", ".", "value", "==", "'Debug'", ":", "build_directory", "=", "join_path", "(", "build_directory", ",", "'build'", ",", "'debug'", ")", "else", ":", "build_directory", "=", "join_path", "(", "build_directory", ",", "'build'", ",", "'release'", ")", "return", "build_directory" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/var/spack/repos/builtin/packages/aocl-sparse/package.py#L41-L54
Kkevsterrr/backdoorme
f9755ca6cec600335e681752e7a1c5c617bb5a39
backdoors/shell/__pupy/rpyc/utils/classic.py
python
connect
(host, port = DEFAULT_SERVER_PORT, ipv6 = False, keepalive = False)
return factory.connect(host, port, SlaveService, ipv6 = ipv6, keepalive = keepalive)
Creates a socket connection to the given host and port. :param host: the host to connect to :param port: the TCP port :param ipv6: whether to create an IPv6 socket or IPv4 :returns: an RPyC connection exposing ``SlaveService``
Creates a socket connection to the given host and port. :param host: the host to connect to :param port: the TCP port :param ipv6: whether to create an IPv6 socket or IPv4 :returns: an RPyC connection exposing ``SlaveService``
[ "Creates", "a", "socket", "connection", "to", "the", "given", "host", "and", "port", ".", ":", "param", "host", ":", "the", "host", "to", "connect", "to", ":", "param", "port", ":", "the", "TCP", "port", ":", "param", "ipv6", ":", "whether", "to", "create", "an", "IPv6", "socket", "or", "IPv4", ":", "returns", ":", "an", "RPyC", "connection", "exposing", "SlaveService" ]
def connect(host, port = DEFAULT_SERVER_PORT, ipv6 = False, keepalive = False): """ Creates a socket connection to the given host and port. :param host: the host to connect to :param port: the TCP port :param ipv6: whether to create an IPv6 socket or IPv4 :returns: an RPyC connection exposing ``SlaveService`` """ return factory.connect(host, port, SlaveService, ipv6 = ipv6, keepalive = keepalive)
[ "def", "connect", "(", "host", ",", "port", "=", "DEFAULT_SERVER_PORT", ",", "ipv6", "=", "False", ",", "keepalive", "=", "False", ")", ":", "return", "factory", ".", "connect", "(", "host", ",", "port", ",", "SlaveService", ",", "ipv6", "=", "ipv6", ",", "keepalive", "=", "keepalive", ")" ]
https://github.com/Kkevsterrr/backdoorme/blob/f9755ca6cec600335e681752e7a1c5c617bb5a39/backdoors/shell/__pupy/rpyc/utils/classic.py#L58-L68
box/box-python-sdk
e8abbb515cfe77d9533df77c807d55d6b494ceaa
boxsdk/object/file.py
python
File.delete_version
(self, file_version: 'FileVersion', etag: Optional[str] = None)
return response.ok
Delete a specific version of a file. :param file_version: The file version to delete. :param etag: If specified, instruct the Box API to update the item only if the current version's etag matches. :returns: Whether the operation succeeded.
Delete a specific version of a file.
[ "Delete", "a", "specific", "version", "of", "a", "file", "." ]
def delete_version(self, file_version: 'FileVersion', etag: Optional[str] = None) -> bool: """ Delete a specific version of a file. :param file_version: The file version to delete. :param etag: If specified, instruct the Box API to update the item only if the current version's etag matches. :returns: Whether the operation succeeded. """ url = self.get_url('versions', file_version.object_id) headers = {'If-Match': etag} if etag is not None else None response = self._session.delete(url, expect_json_response=False, headers=headers) return response.ok
[ "def", "delete_version", "(", "self", ",", "file_version", ":", "'FileVersion'", ",", "etag", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "bool", ":", "url", "=", "self", ".", "get_url", "(", "'versions'", ",", "file_version", ".", "object_id", ")", "headers", "=", "{", "'If-Match'", ":", "etag", "}", "if", "etag", "is", "not", "None", "else", "None", "response", "=", "self", ".", "_session", ".", "delete", "(", "url", ",", "expect_json_response", "=", "False", ",", "headers", "=", "headers", ")", "return", "response", ".", "ok" ]
https://github.com/box/box-python-sdk/blob/e8abbb515cfe77d9533df77c807d55d6b494ceaa/boxsdk/object/file.py#L574-L588
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
streamer/pulp/streamer/cache.py
python
Item.busy
(self)
return self.ref_count > 0
The item is busy. An item with a ref_count > 0 is busy. Returns: bool: True if busy.
The item is busy. An item with a ref_count > 0 is busy.
[ "The", "item", "is", "busy", ".", "An", "item", "with", "a", "ref_count", ">", "0", "is", "busy", "." ]
def busy(self): """ The item is busy. An item with a ref_count > 0 is busy. Returns: bool: True if busy. """ return self.ref_count > 0
[ "def", "busy", "(", "self", ")", ":", "return", "self", ".", "ref_count", ">", "0" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/streamer/pulp/streamer/cache.py#L162-L170
xhtml2pdf/xhtml2pdf
3eef378f869e951448bbf95b7be475f22b659dae
xhtml2pdf/util.py
python
getPos
(position, pagesize)
return getCoords(x, y, None, None, pagesize)
Pair of coordinates
Pair of coordinates
[ "Pair", "of", "coordinates" ]
def getPos(position, pagesize): """ Pair of coordinates """ position = str(position).split() if len(position) != 2: raise Exception("position not defined right way") x, y = [getSize(pos) for pos in position] return getCoords(x, y, None, None, pagesize)
[ "def", "getPos", "(", "position", ",", "pagesize", ")", ":", "position", "=", "str", "(", "position", ")", ".", "split", "(", ")", "if", "len", "(", "position", ")", "!=", "2", ":", "raise", "Exception", "(", "\"position not defined right way\"", ")", "x", ",", "y", "=", "[", "getSize", "(", "pos", ")", "for", "pos", "in", "position", "]", "return", "getCoords", "(", "x", ",", "y", ",", "None", ",", "None", ",", "pagesize", ")" ]
https://github.com/xhtml2pdf/xhtml2pdf/blob/3eef378f869e951448bbf95b7be475f22b659dae/xhtml2pdf/util.py#L418-L426
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_process.py
python
OCProcess.create_obj
(self, obj)
return self._create_from_content(obj['metadata']['name'], obj)
create a resource
create a resource
[ "create", "a", "resource" ]
def create_obj(self, obj): '''create a resource''' return self._create_from_content(obj['metadata']['name'], obj)
[ "def", "create_obj", "(", "self", ",", "obj", ")", ":", "return", "self", ".", "_create_from_content", "(", "obj", "[", "'metadata'", "]", "[", "'name'", "]", ",", "obj", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_process.py#L1523-L1525
steveKapturowski/tensorflow-rl
6dc58da69bad0349a646cfc94ea9c5d1eada8351
algorithms/policy_based_actor_learner.py
python
BaseA3CLearner.bootstrap_value
(self, state, episode_over)
return R
[]
def bootstrap_value(self, state, episode_over): if episode_over: R = 0 else: R = self.session.run( self.local_network.output_layer_v, feed_dict={self.local_network.input_ph:[state]})[0][0] return R
[ "def", "bootstrap_value", "(", "self", ",", "state", ",", "episode_over", ")", ":", "if", "episode_over", ":", "R", "=", "0", "else", ":", "R", "=", "self", ".", "session", ".", "run", "(", "self", ".", "local_network", ".", "output_layer_v", ",", "feed_dict", "=", "{", "self", ".", "local_network", ".", "input_ph", ":", "[", "state", "]", "}", ")", "[", "0", "]", "[", "0", "]", "return", "R" ]
https://github.com/steveKapturowski/tensorflow-rl/blob/6dc58da69bad0349a646cfc94ea9c5d1eada8351/algorithms/policy_based_actor_learner.py#L35-L43
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/cui/settings.py
python
PhonopySettings.set_random_seed
(self, val)
Set random_seed.
Set random_seed.
[ "Set", "random_seed", "." ]
def set_random_seed(self, val): """Set random_seed.""" self._v["random_seed"] = val
[ "def", "set_random_seed", "(", "self", ",", "val", ")", ":", "self", ".", "_v", "[", "\"random_seed\"", "]", "=", "val" ]
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/cui/settings.py#L1388-L1390
sopel-irc/sopel
787baa6e39f9dad57d94600c92e10761c41b21ef
sopel/modules/emoticons.py
python
smirk
(bot, trigger)
[]
def smirk(bot, trigger): bot.say('(¬‿¬)')
[ "def", "smirk", "(", "bot", ",", "trigger", ")", ":", "bot", ".", "say", "(", "'(¬‿¬)')", "" ]
https://github.com/sopel-irc/sopel/blob/787baa6e39f9dad57d94600c92e10761c41b21ef/sopel/modules/emoticons.py#L29-L30
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/encodings/iso8859_11.py
python
Codec.encode
(self,input,errors='strict')
return codecs.charmap_encode(input,errors,encoding_table)
[]
def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table)
[ "def", "encode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "return", "codecs", ".", "charmap_encode", "(", "input", ",", "errors", ",", "encoding_table", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/encodings/iso8859_11.py#L11-L12
garethdmm/gryphon
73e19fa2d0b64c3fc7dac9e0036fc92e25e5b694
gryphon/execution/bots/bank.py
python
account_num_to_key
(account_num)
return reverse_map[account_num]
Convert from BMO account number to exchange database key. eg: '2423 xxxx-xxx' -> 'BMO_USD' Requires the <KEY>_ACCOUNT_NUMBER env vars to be set.
Convert from BMO account number to exchange database key.
[ "Convert", "from", "BMO", "account", "number", "to", "exchange", "database", "key", "." ]
def account_num_to_key(account_num): """ Convert from BMO account number to exchange database key. eg: '2423 xxxx-xxx' -> 'BMO_USD' Requires the <KEY>_ACCOUNT_NUMBER env vars to be set. """ accounts_map = load_accounts_map() reverse_map = {num: key for key, num in accounts_map.items()} return reverse_map[account_num]
[ "def", "account_num_to_key", "(", "account_num", ")", ":", "accounts_map", "=", "load_accounts_map", "(", ")", "reverse_map", "=", "{", "num", ":", "key", "for", "key", ",", "num", "in", "accounts_map", ".", "items", "(", ")", "}", "return", "reverse_map", "[", "account_num", "]" ]
https://github.com/garethdmm/gryphon/blob/73e19fa2d0b64c3fc7dac9e0036fc92e25e5b694/gryphon/execution/bots/bank.py#L250-L260
timonwong/OmniMarkupPreviewer
21921ac7a99d2b5924a2219b33679a5b53621392
OmniMarkupLib/Renderers/libs/python2/docutils/utils/math/math2html.py
python
ContainerSize.styleparameter
(self, name)
return ''
Get the style for a single parameter.
Get the style for a single parameter.
[ "Get", "the", "style", "for", "a", "single", "parameter", "." ]
def styleparameter(self, name): "Get the style for a single parameter." value = getattr(self, name) if value: return name.replace('max', 'max-') + ': ' + value + '; ' return ''
[ "def", "styleparameter", "(", "self", ",", "name", ")", ":", "value", "=", "getattr", "(", "self", ",", "name", ")", "if", "value", ":", "return", "name", ".", "replace", "(", "'max'", ",", "'max-'", ")", "+", "': '", "+", "value", "+", "'; '", "return", "''" ]
https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/Renderers/libs/python2/docutils/utils/math/math2html.py#L3431-L3436
dask/dask-ml
5466bec75bd602cd537cb0dd423dd88520fbf466
dask_ml/cluster/spectral.py
python
_slice_mostly_sorted
(array, keep, rest, ind=None)
return result
Slice dask array `array` that is almost entirely sorted already. We perform approximately `2 * len(keep)` slices on `array`. This is OK, since `keep` is small. Individually, each of these slices is entirely sorted. Parameters ---------- array : dask.array.Array keep : ndarray[Int] This must be sorted. rest : ndarray[Bool] ind : ndarray[Int], optional Returns ------- sliced : dask.array.Array
Slice dask array `array` that is almost entirely sorted already.
[ "Slice", "dask", "array", "array", "that", "is", "almost", "entirely", "sorted", "already", "." ]
def _slice_mostly_sorted(array, keep, rest, ind=None): """Slice dask array `array` that is almost entirely sorted already. We perform approximately `2 * len(keep)` slices on `array`. This is OK, since `keep` is small. Individually, each of these slices is entirely sorted. Parameters ---------- array : dask.array.Array keep : ndarray[Int] This must be sorted. rest : ndarray[Bool] ind : ndarray[Int], optional Returns ------- sliced : dask.array.Array """ if ind is None: ind = np.arange(len(array)) idx = np.argsort(np.concatenate([keep, ind[rest]])) slices = [] if keep[0] > 0: # avoid creating empty slices slices.append(slice(None, keep[0])) slices.append([keep[0]]) windows = zip(keep[:-1], keep[1:]) for l, r in windows: if r > l + 1: # avoid creating empty slices slices.append(slice(l + 1, r)) slices.append([r]) if keep[-1] < len(array) - 1: # avoid creating empty slices slices.append(slice(keep[-1] + 1, None)) result = da.concatenate([array[idx[slice_]] for slice_ in slices]) return result
[ "def", "_slice_mostly_sorted", "(", "array", ",", "keep", ",", "rest", ",", "ind", "=", "None", ")", ":", "if", "ind", "is", "None", ":", "ind", "=", "np", ".", "arange", "(", "len", "(", "array", ")", ")", "idx", "=", "np", ".", "argsort", "(", "np", ".", "concatenate", "(", "[", "keep", ",", "ind", "[", "rest", "]", "]", ")", ")", "slices", "=", "[", "]", "if", "keep", "[", "0", "]", ">", "0", ":", "# avoid creating empty slices", "slices", ".", "append", "(", "slice", "(", "None", ",", "keep", "[", "0", "]", ")", ")", "slices", ".", "append", "(", "[", "keep", "[", "0", "]", "]", ")", "windows", "=", "zip", "(", "keep", "[", ":", "-", "1", "]", ",", "keep", "[", "1", ":", "]", ")", "for", "l", ",", "r", "in", "windows", ":", "if", "r", ">", "l", "+", "1", ":", "# avoid creating empty slices", "slices", ".", "append", "(", "slice", "(", "l", "+", "1", ",", "r", ")", ")", "slices", ".", "append", "(", "[", "r", "]", ")", "if", "keep", "[", "-", "1", "]", "<", "len", "(", "array", ")", "-", "1", ":", "# avoid creating empty slices", "slices", ".", "append", "(", "slice", "(", "keep", "[", "-", "1", "]", "+", "1", ",", "None", ")", ")", "result", "=", "da", ".", "concatenate", "(", "[", "array", "[", "idx", "[", "slice_", "]", "]", "for", "slice_", "in", "slices", "]", ")", "return", "result" ]
https://github.com/dask/dask-ml/blob/5466bec75bd602cd537cb0dd423dd88520fbf466/dask_ml/cluster/spectral.py#L337-L374
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/parsers/iourt42.py
python
Iourt42Client.auth_by_pbid
(self)
Authorize this client using his PBID.
Authorize this client using his PBID.
[ "Authorize", "this", "client", "using", "his", "PBID", "." ]
def auth_by_pbid(self): """ Authorize this client using his PBID. """ self.console.debug("Auth by FSA: %r", self.pbid) clients_matching_pbid = self.console.storage.getClientsMatching(dict(pbid=self.pbid)) if len(clients_matching_pbid) > 1: self.console.warning("Found %s client having FSA '%s'", len(clients_matching_pbid), self.pbid) return self.auth_by_pbid_and_guid() elif len(clients_matching_pbid) == 1: self.id = clients_matching_pbid[0].id # we may have a second client entry in database with current guid. # we want to update our current client guid only if it is not the case. try: client_by_guid = self.console.storage.getClient(Iourt42Client(guid=self.guid)) except KeyError: pass else: if client_by_guid.id != self.id: # so storage.getClient is able to overwrite the value which will make # it remain unchanged in database when .save() will be called later on self._guid = None return self.console.storage.getClient(self) else: self.console.debug('Frozen Sand account [%s] unknown in database', self.pbid) return False
[ "def", "auth_by_pbid", "(", "self", ")", ":", "self", ".", "console", ".", "debug", "(", "\"Auth by FSA: %r\"", ",", "self", ".", "pbid", ")", "clients_matching_pbid", "=", "self", ".", "console", ".", "storage", ".", "getClientsMatching", "(", "dict", "(", "pbid", "=", "self", ".", "pbid", ")", ")", "if", "len", "(", "clients_matching_pbid", ")", ">", "1", ":", "self", ".", "console", ".", "warning", "(", "\"Found %s client having FSA '%s'\"", ",", "len", "(", "clients_matching_pbid", ")", ",", "self", ".", "pbid", ")", "return", "self", ".", "auth_by_pbid_and_guid", "(", ")", "elif", "len", "(", "clients_matching_pbid", ")", "==", "1", ":", "self", ".", "id", "=", "clients_matching_pbid", "[", "0", "]", ".", "id", "# we may have a second client entry in database with current guid.", "# we want to update our current client guid only if it is not the case.", "try", ":", "client_by_guid", "=", "self", ".", "console", ".", "storage", ".", "getClient", "(", "Iourt42Client", "(", "guid", "=", "self", ".", "guid", ")", ")", "except", "KeyError", ":", "pass", "else", ":", "if", "client_by_guid", ".", "id", "!=", "self", ".", "id", ":", "# so storage.getClient is able to overwrite the value which will make", "# it remain unchanged in database when .save() will be called later on", "self", ".", "_guid", "=", "None", "return", "self", ".", "console", ".", "storage", ".", "getClient", "(", "self", ")", "else", ":", "self", ".", "console", ".", "debug", "(", "'Frozen Sand account [%s] unknown in database'", ",", "self", ".", "pbid", ")", "return", "False" ]
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/parsers/iourt42.py#L54-L79
Parsl/parsl
af2535341152b2640fdd1a3b73b891992bf1b3ea
parsl/channels/local/local.py
python
LocalChannel.push_file
(self, source, dest_dir)
return local_dest
If the source files dirpath is the same as dest_dir, a copy is not necessary, and nothing is done. Else a copy is made. Args: - source (string) : Path to the source file - dest_dir (string) : Path to the directory to which the files is to be copied Returns: - destination_path (String) : Absolute path of the destination file Raises: - FileCopyException : If file copy failed.
If the source files dirpath is the same as dest_dir, a copy is not necessary, and nothing is done. Else a copy is made.
[ "If", "the", "source", "files", "dirpath", "is", "the", "same", "as", "dest_dir", "a", "copy", "is", "not", "necessary", "and", "nothing", "is", "done", ".", "Else", "a", "copy", "is", "made", "." ]
def push_file(self, source, dest_dir): ''' If the source files dirpath is the same as dest_dir, a copy is not necessary, and nothing is done. Else a copy is made. Args: - source (string) : Path to the source file - dest_dir (string) : Path to the directory to which the files is to be copied Returns: - destination_path (String) : Absolute path of the destination file Raises: - FileCopyException : If file copy failed. ''' local_dest = os.path.join(dest_dir, os.path.basename(source)) # Only attempt to copy if the target dir and source dir are different if os.path.dirname(source) != dest_dir: try: shutil.copyfile(source, local_dest) os.chmod(local_dest, 0o777) except OSError as e: raise FileCopyException(e, self.hostname) else: os.chmod(local_dest, 0o777) return local_dest
[ "def", "push_file", "(", "self", ",", "source", ",", "dest_dir", ")", ":", "local_dest", "=", "os", ".", "path", ".", "join", "(", "dest_dir", ",", "os", ".", "path", ".", "basename", "(", "source", ")", ")", "# Only attempt to copy if the target dir and source dir are different", "if", "os", ".", "path", ".", "dirname", "(", "source", ")", "!=", "dest_dir", ":", "try", ":", "shutil", ".", "copyfile", "(", "source", ",", "local_dest", ")", "os", ".", "chmod", "(", "local_dest", ",", "0o777", ")", "except", "OSError", "as", "e", ":", "raise", "FileCopyException", "(", "e", ",", "self", ".", "hostname", ")", "else", ":", "os", ".", "chmod", "(", "local_dest", ",", "0o777", ")", "return", "local_dest" ]
https://github.com/Parsl/parsl/blob/af2535341152b2640fdd1a3b73b891992bf1b3ea/parsl/channels/local/local.py#L80-L109
celery/celery
95015a1d5a60d94d8e1e02da4b9cf16416c747e2
celery/backends/azureblockblob.py
python
AzureBlockBlobBackend.get
(self, key)
Read the value stored at the given key. Args: key: The key for which to read the value.
Read the value stored at the given key.
[ "Read", "the", "value", "stored", "at", "the", "given", "key", "." ]
def get(self, key): """Read the value stored at the given key. Args: key: The key for which to read the value. """ key = bytes_to_str(key) LOGGER.debug("Getting Azure Block Blob %s/%s", self._container_name, key) blob_client = self._blob_service_client.get_blob_client( container=self._container_name, blob=f'{self.base_path}{key}', ) try: return blob_client.download_blob().readall().decode() except ResourceNotFoundError: return None
[ "def", "get", "(", "self", ",", "key", ")", ":", "key", "=", "bytes_to_str", "(", "key", ")", "LOGGER", ".", "debug", "(", "\"Getting Azure Block Blob %s/%s\"", ",", "self", ".", "_container_name", ",", "key", ")", "blob_client", "=", "self", ".", "_blob_service_client", ".", "get_blob_client", "(", "container", "=", "self", ".", "_container_name", ",", "blob", "=", "f'{self.base_path}{key}'", ",", ")", "try", ":", "return", "blob_client", ".", "download_blob", "(", ")", ".", "readall", "(", ")", ".", "decode", "(", ")", "except", "ResourceNotFoundError", ":", "return", "None" ]
https://github.com/celery/celery/blob/95015a1d5a60d94d8e1e02da4b9cf16416c747e2/celery/backends/azureblockblob.py#L85-L102
golemhq/golem
84f51478b169cdeab73fc7e2a22a64d0a2a29263
golem/actions.py
python
verify_element_checked
(element)
Verify element is checked. This applies to checkboxes and radio buttons. Parameters: element : element
Verify element is checked. This applies to checkboxes and radio buttons.
[ "Verify", "element", "is", "checked", ".", "This", "applies", "to", "checkboxes", "and", "radio", "buttons", "." ]
def verify_element_checked(element): """Verify element is checked. This applies to checkboxes and radio buttons. Parameters: element : element """ element = get_browser().find(element, timeout=0) with _verify_step(f'Verify element {element.name} is checked') as s: s.error = f'element {element.name} is not checked' s.condition = element.is_selected()
[ "def", "verify_element_checked", "(", "element", ")", ":", "element", "=", "get_browser", "(", ")", ".", "find", "(", "element", ",", "timeout", "=", "0", ")", "with", "_verify_step", "(", "f'Verify element {element.name} is checked'", ")", "as", "s", ":", "s", ".", "error", "=", "f'element {element.name} is not checked'", "s", ".", "condition", "=", "element", ".", "is_selected", "(", ")" ]
https://github.com/golemhq/golem/blob/84f51478b169cdeab73fc7e2a22a64d0a2a29263/golem/actions.py#L1966-L1976
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/keyword_plan_service/client.py
python
KeywordPlanServiceClient.mutate_keyword_plans
( self, request: Union[ keyword_plan_service.MutateKeywordPlansRequest, dict ] = None, *, customer_id: str = None, operations: Sequence[keyword_plan_service.KeywordPlanOperation] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
return response
r"""Creates, updates, or removes keyword plans. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `KeywordPlanError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `QuotaError <>`__ `RequestError <>`__ `ResourceCountLimitExceededError <>`__ `StringLengthError <>`__ Args: request (Union[google.ads.googleads.v9.services.types.MutateKeywordPlansRequest, dict]): The request object. Request message for [KeywordPlanService.MutateKeywordPlans][google.ads.googleads.v9.services.KeywordPlanService.MutateKeywordPlans]. customer_id (:class:`str`): Required. The ID of the customer whose keyword plans are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (:class:`Sequence[google.ads.googleads.v9.services.types.KeywordPlanOperation]`): Required. The list of operations to perform on individual keyword plans. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v9.services.types.MutateKeywordPlansResponse: Response message for a keyword plan mutate.
r"""Creates, updates, or removes keyword plans. Operation statuses are returned.
[ "r", "Creates", "updates", "or", "removes", "keyword", "plans", ".", "Operation", "statuses", "are", "returned", "." ]
def mutate_keyword_plans( self, request: Union[ keyword_plan_service.MutateKeywordPlansRequest, dict ] = None, *, customer_id: str = None, operations: Sequence[keyword_plan_service.KeywordPlanOperation] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> keyword_plan_service.MutateKeywordPlansResponse: r"""Creates, updates, or removes keyword plans. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `KeywordPlanError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `QuotaError <>`__ `RequestError <>`__ `ResourceCountLimitExceededError <>`__ `StringLengthError <>`__ Args: request (Union[google.ads.googleads.v9.services.types.MutateKeywordPlansRequest, dict]): The request object. Request message for [KeywordPlanService.MutateKeywordPlans][google.ads.googleads.v9.services.KeywordPlanService.MutateKeywordPlans]. customer_id (:class:`str`): Required. The ID of the customer whose keyword plans are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (:class:`Sequence[google.ads.googleads.v9.services.types.KeywordPlanOperation]`): Required. The list of operations to perform on individual keyword plans. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v9.services.types.MutateKeywordPlansResponse: Response message for a keyword plan mutate. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([customer_id, operations]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a keyword_plan_service.MutateKeywordPlansRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, keyword_plan_service.MutateKeywordPlansRequest ): request = keyword_plan_service.MutateKeywordPlansRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if operations is not None: request.operations = operations # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.mutate_keyword_plans ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response
[ "def", "mutate_keyword_plans", "(", "self", ",", "request", ":", "Union", "[", "keyword_plan_service", ".", "MutateKeywordPlansRequest", ",", "dict", "]", "=", "None", ",", "*", ",", "customer_id", ":", "str", "=", "None", ",", "operations", ":", "Sequence", "[", "keyword_plan_service", ".", "KeywordPlanOperation", "]", "=", "None", ",", "retry", ":", "OptionalRetry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "(", ")", ",", ")", "->", "keyword_plan_service", ".", "MutateKeywordPlansResponse", ":", "# Create or coerce a protobuf request object.", "# Sanity check: If we got a request object, we should *not* have", "# gotten any keyword arguments that map to the request.", "if", "request", "is", "not", "None", "and", "any", "(", "[", "customer_id", ",", "operations", "]", ")", ":", "raise", "ValueError", "(", "\"If the `request` argument is set, then none of \"", "\"the individual field arguments should be set.\"", ")", "# Minor optimization to avoid making a copy if the user passes", "# in a keyword_plan_service.MutateKeywordPlansRequest.", "# There's no risk of modifying the input as we've already verified", "# there are no flattened fields.", "if", "not", "isinstance", "(", "request", ",", "keyword_plan_service", ".", "MutateKeywordPlansRequest", ")", ":", "request", "=", "keyword_plan_service", ".", "MutateKeywordPlansRequest", "(", "request", ")", "# If we have keyword arguments corresponding to fields on the", "# request, apply these.", "if", "customer_id", "is", "not", "None", ":", "request", ".", "customer_id", "=", "customer_id", "if", "operations", "is", "not", "None", ":", "request", ".", "operations", "=", "operations", "# Wrap the RPC method; this adds retry and timeout information,", "# and friendly error handling.", "rpc", "=", "self", ".", "_transport", ".", "_wrapped_methods", "[", "self", ".", "_transport", ".", "mutate_keyword_plans", "]", "# Certain fields should be provided within the metadata header;", "# add these here.", "metadata", "=", "tuple", "(", "metadata", ")", "+", "(", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "(", "(", "\"customer_id\"", ",", "request", ".", "customer_id", ")", ",", ")", ")", ",", ")", "# Send the request.", "response", "=", "rpc", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", "# Done; return the response.", "return", "response" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/keyword_plan_service/client.py#L455-L551
rackerlabs/mimic
efd34108b6aa3eb7ecd26e22f1aa155c14a7885e
mimic/rest/maas_api.py
python
MaasMock.delete_notification_plan
(self, request, tenant_id, np_id)
return b''
Remove a notification plan
Remove a notification plan
[ "Remove", "a", "notification", "plan" ]
def delete_notification_plan(self, request, tenant_id, np_id): """ Remove a notification plan """ notification_plans = self._entity_cache_for_tenant( tenant_id).notification_plans entities = self._entity_cache_for_tenant(tenant_id).entities alarmids_using_np = [alarm.id for entity in entities.values() for alarm in entity.alarms.values() if alarm.notification_plan_id == np_id] if len(alarmids_using_np): status = 403 request.setResponseCode(status) err_message = ('Notification plans cannot be removed while alarms ' + 'are using it: {0}'.format(' '.join(alarmids_using_np))) self._audit('notification_plans', request, tenant_id, status) return json.dumps({'type': 'forbiddenError', 'code': status, 'txnId': '.fake.mimic.transaction.id.c-1111111.ts-123444444.v-12344frf', 'message': err_message, 'details': err_message}) try: _delete_notification_plan(notification_plans, np_id) except ObjectDoesNotExist as e: request.setResponseCode(e.code) self._audit('notification_plans', request, tenant_id, e.code) return json.dumps(e.to_json()) status = 204 request.setResponseCode(status) self._audit('notification_plans', request, tenant_id, status) request.setHeader(b'content-type', b'text/plain') return b''
[ "def", "delete_notification_plan", "(", "self", ",", "request", ",", "tenant_id", ",", "np_id", ")", ":", "notification_plans", "=", "self", ".", "_entity_cache_for_tenant", "(", "tenant_id", ")", ".", "notification_plans", "entities", "=", "self", ".", "_entity_cache_for_tenant", "(", "tenant_id", ")", ".", "entities", "alarmids_using_np", "=", "[", "alarm", ".", "id", "for", "entity", "in", "entities", ".", "values", "(", ")", "for", "alarm", "in", "entity", ".", "alarms", ".", "values", "(", ")", "if", "alarm", ".", "notification_plan_id", "==", "np_id", "]", "if", "len", "(", "alarmids_using_np", ")", ":", "status", "=", "403", "request", ".", "setResponseCode", "(", "status", ")", "err_message", "=", "(", "'Notification plans cannot be removed while alarms '", "+", "'are using it: {0}'", ".", "format", "(", "' '", ".", "join", "(", "alarmids_using_np", ")", ")", ")", "self", ".", "_audit", "(", "'notification_plans'", ",", "request", ",", "tenant_id", ",", "status", ")", "return", "json", ".", "dumps", "(", "{", "'type'", ":", "'forbiddenError'", ",", "'code'", ":", "status", ",", "'txnId'", ":", "'.fake.mimic.transaction.id.c-1111111.ts-123444444.v-12344frf'", ",", "'message'", ":", "err_message", ",", "'details'", ":", "err_message", "}", ")", "try", ":", "_delete_notification_plan", "(", "notification_plans", ",", "np_id", ")", "except", "ObjectDoesNotExist", "as", "e", ":", "request", ".", "setResponseCode", "(", "e", ".", "code", ")", "self", ".", "_audit", "(", "'notification_plans'", ",", "request", ",", "tenant_id", ",", "e", ".", "code", ")", "return", "json", ".", "dumps", "(", "e", ".", "to_json", "(", ")", ")", "status", "=", "204", "request", ".", "setResponseCode", "(", "status", ")", "self", ".", "_audit", "(", "'notification_plans'", ",", "request", ",", "tenant_id", ",", "status", ")", "request", ".", "setHeader", "(", "b'content-type'", ",", "b'text/plain'", ")", "return", "b''" ]
https://github.com/rackerlabs/mimic/blob/efd34108b6aa3eb7ecd26e22f1aa155c14a7885e/mimic/rest/maas_api.py#L1392-L1427
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/ldap3/core/connection.py
python
Connection.__exit__
(self, exc_type, exc_val, exc_tb)
[]
def __exit__(self, exc_type, exc_val, exc_tb): with self.connection_lock: context_bound, context_closed = self._context_state.pop() if (not context_bound and self.bound) or self.stream: # restore status prior to entering context try: self.unbind() except LDAPExceptionError: pass if not context_closed and self.closed: self.open() if exc_type is not None: if log_enabled(ERROR): log(ERROR, '%s for <%s>', exc_type, self) return False
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_val", ",", "exc_tb", ")", ":", "with", "self", ".", "connection_lock", ":", "context_bound", ",", "context_closed", "=", "self", ".", "_context_state", ".", "pop", "(", ")", "if", "(", "not", "context_bound", "and", "self", ".", "bound", ")", "or", "self", ".", "stream", ":", "# restore status prior to entering context", "try", ":", "self", ".", "unbind", "(", ")", "except", "LDAPExceptionError", ":", "pass", "if", "not", "context_closed", "and", "self", ".", "closed", ":", "self", ".", "open", "(", ")", "if", "exc_type", "is", "not", "None", ":", "if", "log_enabled", "(", "ERROR", ")", ":", "log", "(", "ERROR", ",", "'%s for <%s>'", ",", "exc_type", ",", "self", ")", "return", "False" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/ldap3/core/connection.py#L517-L532
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3aaa.py
python
AuthS3.s3_logged_in_human_resource
(self)
return row.id if row else None
Get the first HR record ID for the current logged-in user
Get the first HR record ID for the current logged-in user
[ "Get", "the", "first", "HR", "record", "ID", "for", "the", "current", "logged", "-", "in", "user" ]
def s3_logged_in_human_resource(self): """ Get the first HR record ID for the current logged-in user """ row = None if self.s3_logged_in(): s3db = current.s3db ptable = s3db.pr_person htable = s3db.hrm_human_resource try: query = (htable.person_id == ptable.id) & \ (ptable.pe_id == self.user.pe_id) except AttributeError: # Prepop (auth.override, self.user is None) pass else: row = current.db(query).select(htable.id, limitby = (0, 1), orderby = ~htable.modified_on, ).first() return row.id if row else None
[ "def", "s3_logged_in_human_resource", "(", "self", ")", ":", "row", "=", "None", "if", "self", ".", "s3_logged_in", "(", ")", ":", "s3db", "=", "current", ".", "s3db", "ptable", "=", "s3db", ".", "pr_person", "htable", "=", "s3db", ".", "hrm_human_resource", "try", ":", "query", "=", "(", "htable", ".", "person_id", "==", "ptable", ".", "id", ")", "&", "(", "ptable", ".", "pe_id", "==", "self", ".", "user", ".", "pe_id", ")", "except", "AttributeError", ":", "# Prepop (auth.override, self.user is None)", "pass", "else", ":", "row", "=", "current", ".", "db", "(", "query", ")", ".", "select", "(", "htable", ".", "id", ",", "limitby", "=", "(", "0", ",", "1", ")", ",", "orderby", "=", "~", "htable", ".", "modified_on", ",", ")", ".", "first", "(", ")", "return", "row", ".", "id", "if", "row", "else", "None" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3aaa.py#L4679-L4702
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/redis/client.py
python
StrictRedis.expire
(self, name, time)
return self.execute_command('EXPIRE', name, time)
Set an expire flag on key ``name`` for ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
Set an expire flag on key ``name`` for ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
[ "Set", "an", "expire", "flag", "on", "key", "name", "for", "time", "seconds", ".", "time", "can", "be", "represented", "by", "an", "integer", "or", "a", "Python", "timedelta", "object", "." ]
def expire(self, name, time): """ Set an expire flag on key ``name`` for ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if isinstance(time, datetime.timedelta): time = time.seconds + time.days * 24 * 3600 return self.execute_command('EXPIRE', name, time)
[ "def", "expire", "(", "self", ",", "name", ",", "time", ")", ":", "if", "isinstance", "(", "time", ",", "datetime", ".", "timedelta", ")", ":", "time", "=", "time", ".", "seconds", "+", "time", ".", "days", "*", "24", "*", "3600", "return", "self", ".", "execute_command", "(", "'EXPIRE'", ",", "name", ",", "time", ")" ]
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/redis/client.py#L858-L865
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/sqlalchemy/dialects/firebird/base.py
python
FBDDLCompiler.visit_drop_sequence
(self, drop)
Generate a ``DROP GENERATOR`` statement for the sequence.
Generate a ``DROP GENERATOR`` statement for the sequence.
[ "Generate", "a", "DROP", "GENERATOR", "statement", "for", "the", "sequence", "." ]
def visit_drop_sequence(self, drop): """Generate a ``DROP GENERATOR`` statement for the sequence.""" if self.dialect._version_two: return "DROP SEQUENCE %s" % \ self.preparer.format_sequence(drop.element) else: return "DROP GENERATOR %s" % \ self.preparer.format_sequence(drop.element)
[ "def", "visit_drop_sequence", "(", "self", ",", "drop", ")", ":", "if", "self", ".", "dialect", ".", "_version_two", ":", "return", "\"DROP SEQUENCE %s\"", "%", "self", ".", "preparer", ".", "format_sequence", "(", "drop", ".", "element", ")", "else", ":", "return", "\"DROP GENERATOR %s\"", "%", "self", ".", "preparer", ".", "format_sequence", "(", "drop", ".", "element", ")" ]
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/dialects/firebird/base.py#L317-L325
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/logging/logging_management_client.py
python
LoggingManagementClient.get_log_saved_search
(self, log_saved_search_id, **kwargs)
Retrieves a log saved search. :param str log_saved_search_id: (required) OCID of the logSavedSearch :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.logging.models.LogSavedSearch` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/logging/get_log_saved_search.py.html>`__ to see an example of how to use get_log_saved_search API.
Retrieves a log saved search.
[ "Retrieves", "a", "log", "saved", "search", "." ]
def get_log_saved_search(self, log_saved_search_id, **kwargs): """ Retrieves a log saved search. :param str log_saved_search_id: (required) OCID of the logSavedSearch :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.logging.models.LogSavedSearch` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/logging/get_log_saved_search.py.html>`__ to see an example of how to use get_log_saved_search API. """ resource_path = "/logSavedSearches/{logSavedSearchId}" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "get_log_saved_search got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "logSavedSearchId": log_saved_search_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="LogSavedSearch") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="LogSavedSearch")
[ "def", "get_log_saved_search", "(", "self", ",", "log_saved_search_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/logSavedSearches/{logSavedSearchId}\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"opc_request_id\"", "]", "extra_kwargs", "=", "[", "_key", "for", "_key", "in", "six", ".", "iterkeys", "(", "kwargs", ")", "if", "_key", "not", "in", "expected_kwargs", "]", "if", "extra_kwargs", ":", "raise", "ValueError", "(", "\"get_log_saved_search got unknown kwargs: {!r}\"", ".", "format", "(", "extra_kwargs", ")", ")", "path_params", "=", "{", "\"logSavedSearchId\"", ":", "log_saved_search_id", "}", "path_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", "if", "v", "is", "not", "missing", "}", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", ":", "if", "v", "is", "None", "or", "(", "isinstance", "(", "v", ",", "six", ".", "string_types", ")", "and", "len", "(", "v", ".", "strip", "(", ")", ")", "==", "0", ")", ":", "raise", "ValueError", "(", "'Parameter {} cannot be None, whitespace or empty string'", ".", "format", "(", "k", ")", ")", "header_params", "=", "{", "\"accept\"", ":", "\"application/json\"", ",", "\"content-type\"", ":", "\"application/json\"", ",", "\"opc-request-id\"", ":", "kwargs", ".", "get", "(", "\"opc_request_id\"", ",", "missing", ")", "}", "header_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "header_params", ")", "if", "v", "is", "not", "missing", "and", "v", "is", "not", "None", "}", "retry_strategy", "=", "self", ".", "base_client", ".", "get_preferred_retry_strategy", "(", "operation_retry_strategy", "=", "kwargs", ".", "get", "(", "'retry_strategy'", ")", ",", "client_retry_strategy", "=", "self", ".", "retry_strategy", ")", "if", "retry_strategy", ":", "if", "not", "isinstance", "(", "retry_strategy", ",", "retry", ".", "NoneRetryStrategy", ")", ":", "self", ".", "base_client", ".", "add_opc_client_retries_header", "(", "header_params", ")", "retry_strategy", ".", "add_circuit_breaker_callback", "(", "self", ".", "circuit_breaker_callback", ")", "return", "retry_strategy", ".", "make_retrying_call", "(", "self", ".", "base_client", ".", "call_api", ",", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "response_type", "=", "\"LogSavedSearch\"", ")", "else", ":", "return", "self", ".", "base_client", ".", "call_api", "(", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "response_type", "=", "\"LogSavedSearch\"", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/logging/logging_management_client.py#L1533-L1611
pysathq/pysat
07bf3a5a4428d40eca804e7ebdf4f496aadf4213
pysat/solvers.py
python
Mergesat3.interrupt
(self)
Interrupt solver execution.
Interrupt solver execution.
[ "Interrupt", "solver", "execution", "." ]
def interrupt(self): """ Interrupt solver execution. """ if self.mergesat: pysolvers.mergesat3_interrupt(self.mergesat)
[ "def", "interrupt", "(", "self", ")", ":", "if", "self", ".", "mergesat", ":", "pysolvers", ".", "mergesat3_interrupt", "(", "self", ".", "mergesat", ")" ]
https://github.com/pysathq/pysat/blob/07bf3a5a4428d40eca804e7ebdf4f496aadf4213/pysat/solvers.py#L4003-L4009
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/engine/base.py
python
Transaction.close
(self)
Close this :class:`.Transaction`. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing transaction.
Close this :class:`.Transaction`.
[ "Close", "this", ":", "class", ":", ".", "Transaction", "." ]
def close(self): """Close this :class:`.Transaction`. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing transaction. """ if self._parent.is_active and self._parent is self: self.rollback() self.connection._discard_transaction(self)
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_parent", ".", "is_active", "and", "self", ".", "_parent", "is", "self", ":", "self", ".", "rollback", "(", ")", "self", ".", "connection", ".", "_discard_transaction", "(", "self", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/engine/base.py#L1739-L1753
nats-io/nats.py
49635bf58b1c888c66fa37569a9248b1a83a6c0a
nats/aio/msg.py
python
Msg.in_progress
(self)
in_progress acknowledges a message delivered by JetStream is still being worked on. Unlike other types of acks, an in-progress ack (+WPI) can be done multiple times.
in_progress acknowledges a message delivered by JetStream is still being worked on. Unlike other types of acks, an in-progress ack (+WPI) can be done multiple times.
[ "in_progress", "acknowledges", "a", "message", "delivered", "by", "JetStream", "is", "still", "being", "worked", "on", ".", "Unlike", "other", "types", "of", "acks", "an", "in", "-", "progress", "ack", "(", "+", "WPI", ")", "can", "be", "done", "multiple", "times", "." ]
async def in_progress(self): """ in_progress acknowledges a message delivered by JetStream is still being worked on. Unlike other types of acks, an in-progress ack (+WPI) can be done multiple times. """ if self.reply is None or self.reply == '': raise NotJSMessageError await self._client.publish(self.reply, Msg.Ack.Progress)
[ "async", "def", "in_progress", "(", "self", ")", ":", "if", "self", ".", "reply", "is", "None", "or", "self", ".", "reply", "==", "''", ":", "raise", "NotJSMessageError", "await", "self", ".", "_client", ".", "publish", "(", "self", ".", "reply", ",", "Msg", ".", "Ack", ".", "Progress", ")" ]
https://github.com/nats-io/nats.py/blob/49635bf58b1c888c66fa37569a9248b1a83a6c0a/nats/aio/msg.py#L119-L126
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/returns/evaluators.py
python
ValueEvaluator._evaluate
(self, batch)
return [(self._value, values)]
Evaluate the value on the given batch. If None, it will evaluate on the previous batch. Args: batch (Batch): batch containing the transitions / trajectories.
Evaluate the value on the given batch. If None, it will evaluate on the previous batch.
[ "Evaluate", "the", "value", "on", "the", "given", "batch", ".", "If", "None", "it", "will", "evaluate", "on", "the", "previous", "batch", "." ]
def _evaluate(self, batch): """Evaluate the value on the given batch. If None, it will evaluate on the previous batch. Args: batch (Batch): batch containing the transitions / trajectories. """ # evaluate value values = self._value.evaluate(batch['states'], batch['actions']) # return values return [(self._value, values)]
[ "def", "_evaluate", "(", "self", ",", "batch", ")", ":", "# evaluate value", "values", "=", "self", ".", "_value", ".", "evaluate", "(", "batch", "[", "'states'", "]", ",", "batch", "[", "'actions'", "]", ")", "# return values", "return", "[", "(", "self", ".", "_value", ",", "values", ")", "]" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/returns/evaluators.py#L206-L216
kymatio/kymatio
38cead012d1b134843a1dd0d5ea160042037c7da
kymatio/backend/numpy_backend.py
python
cdgmm
(A, B, inplace=False)
Complex pointwise multiplication between (batched) tensor A and tensor B. Parameters ---------- A : tensor A is a complex tensor of size (B, C, M, N, 2) B : tensor B is a complex tensor of size (M, N) or real tensor of (M, N) inplace : boolean, optional if set to True, all the operations are performed inplace Returns ------- C : tensor output tensor of size (B, C, M, N, 2) such that: C[b, c, m, n, :] = A[b, c, m, n, :] * B[m, n, :]
Complex pointwise multiplication between (batched) tensor A and tensor B.
[ "Complex", "pointwise", "multiplication", "between", "(", "batched", ")", "tensor", "A", "and", "tensor", "B", "." ]
def cdgmm(A, B, inplace=False): """ Complex pointwise multiplication between (batched) tensor A and tensor B. Parameters ---------- A : tensor A is a complex tensor of size (B, C, M, N, 2) B : tensor B is a complex tensor of size (M, N) or real tensor of (M, N) inplace : boolean, optional if set to True, all the operations are performed inplace Returns ------- C : tensor output tensor of size (B, C, M, N, 2) such that: C[b, c, m, n, :] = A[b, c, m, n, :] * B[m, n, :] """ if not _is_complex(A): raise TypeError('The first input must be complex.') if A.shape[-len(B.shape):] != B.shape[:]: raise RuntimeError('The inputs are not compatible for ' 'multiplication.') if not _is_complex(B) and not _is_real(B): raise TypeError('The second input must be complex or real.') if inplace: return np.multiply(A, B, out=A) else: return A * B
[ "def", "cdgmm", "(", "A", ",", "B", ",", "inplace", "=", "False", ")", ":", "if", "not", "_is_complex", "(", "A", ")", ":", "raise", "TypeError", "(", "'The first input must be complex.'", ")", "if", "A", ".", "shape", "[", "-", "len", "(", "B", ".", "shape", ")", ":", "]", "!=", "B", ".", "shape", "[", ":", "]", ":", "raise", "RuntimeError", "(", "'The inputs are not compatible for '", "'multiplication.'", ")", "if", "not", "_is_complex", "(", "B", ")", "and", "not", "_is_real", "(", "B", ")", ":", "raise", "TypeError", "(", "'The second input must be complex or real.'", ")", "if", "inplace", ":", "return", "np", ".", "multiply", "(", "A", ",", "B", ",", "out", "=", "A", ")", "else", ":", "return", "A", "*", "B" ]
https://github.com/kymatio/kymatio/blob/38cead012d1b134843a1dd0d5ea160042037c7da/kymatio/backend/numpy_backend.py#L36-L70
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/threading.py
python
_RLock.release
(self)
Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value.
Release a lock, decrementing the recursion level.
[ "Release", "a", "lock", "decrementing", "the", "recursion", "level", "." ]
def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. """ if self.__owner != _get_ident(): raise RuntimeError("cannot release un-acquired lock") self.__count = count = self.__count - 1 if not count: self.__owner = None self.__block.release() if __debug__: self._note("%s.release(): final release", self) else: if __debug__: self._note("%s.release(): non-final release", self)
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "__owner", "!=", "_get_ident", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot release un-acquired lock\"", ")", "self", ".", "__count", "=", "count", "=", "self", ".", "__count", "-", "1", "if", "not", "count", ":", "self", ".", "__owner", "=", "None", "self", ".", "__block", ".", "release", "(", ")", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.release(): final release\"", ",", "self", ")", "else", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.release(): non-final release\"", ",", "self", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/threading.py#L187-L213
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/orm/interfaces.py
python
SessionExtension.before_commit
(self, session)
Execute right before commit is called. Note that this may not be per-flush if a longer running transaction is ongoing.
Execute right before commit is called. Note that this may not be per-flush if a longer running transaction is ongoing.
[ "Execute", "right", "before", "commit", "is", "called", ".", "Note", "that", "this", "may", "not", "be", "per", "-", "flush", "if", "a", "longer", "running", "transaction", "is", "ongoing", "." ]
def before_commit(self, session): """Execute right before commit is called. Note that this may not be per-flush if a longer running transaction is ongoing."""
[ "def", "before_commit", "(", "self", ",", "session", ")", ":" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/orm/interfaces.py#L342-L346
wbond/packagecontrol.io
9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20
app/lib/package_control/clients/gitlab_client.py
python
GitLabClient.make_tags_url
(self, repo)
return 'https://gitlab.com/%s/-/tags' % match.group(1)
Generate the tags URL for a GitLab repo if the value passed is a GitLab repository URL :param repo: The repository URL :return: The tags URL if repo was a GitLab repo, otherwise False
Generate the tags URL for a GitLab repo if the value passed is a GitLab repository URL
[ "Generate", "the", "tags", "URL", "for", "a", "GitLab", "repo", "if", "the", "value", "passed", "is", "a", "GitLab", "repository", "URL" ]
def make_tags_url(self, repo): """ Generate the tags URL for a GitLab repo if the value passed is a GitLab repository URL :param repo: The repository URL :return: The tags URL if repo was a GitLab repo, otherwise False """ match = re.match('https?://gitlab.com/([^/]+/[^/]+)/?$', repo) if not match: return False return 'https://gitlab.com/%s/-/tags' % match.group(1)
[ "def", "make_tags_url", "(", "self", ",", "repo", ")", ":", "match", "=", "re", ".", "match", "(", "'https?://gitlab.com/([^/]+/[^/]+)/?$'", ",", "repo", ")", "if", "not", "match", ":", "return", "False", "return", "'https://gitlab.com/%s/-/tags'", "%", "match", ".", "group", "(", "1", ")" ]
https://github.com/wbond/packagecontrol.io/blob/9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20/app/lib/package_control/clients/gitlab_client.py#L20-L36
openstack/swift
b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100
swift/account/backend.py
python
AccountBroker._migrate_add_container_count
(self, conn)
Add the container_count column to the 'policy_stat' table and update it :param conn: DB connection object
Add the container_count column to the 'policy_stat' table and update it
[ "Add", "the", "container_count", "column", "to", "the", "policy_stat", "table", "and", "update", "it" ]
def _migrate_add_container_count(self, conn): """ Add the container_count column to the 'policy_stat' table and update it :param conn: DB connection object """ # add the container_count column curs = conn.cursor() curs.executescript(''' DROP TRIGGER container_delete_ps; DROP TRIGGER container_insert_ps; ALTER TABLE policy_stat ADD COLUMN container_count INTEGER DEFAULT 0; ''' + POLICY_STAT_TRIGGER_SCRIPT) # keep the simple case simple, if there's only one entry in the # policy_stat table we just copy the total container count from the # account_stat table # if that triggers an update then the where changes <> 0 *would* exist # and the insert or replace from the count subqueries won't execute curs.executescript(""" UPDATE policy_stat SET container_count = ( SELECT container_count FROM account_stat) WHERE ( SELECT COUNT(storage_policy_index) FROM policy_stat ) <= 1; INSERT OR REPLACE INTO policy_stat ( storage_policy_index, container_count, object_count, bytes_used ) SELECT p.storage_policy_index, c.count, p.object_count, p.bytes_used FROM ( SELECT storage_policy_index, COUNT(*) as count FROM container WHERE deleted = 0 GROUP BY storage_policy_index ) c JOIN policy_stat p ON p.storage_policy_index = c.storage_policy_index WHERE NOT EXISTS( SELECT changes() as change FROM policy_stat WHERE change <> 0 ); """) conn.commit()
[ "def", "_migrate_add_container_count", "(", "self", ",", "conn", ")", ":", "# add the container_count column", "curs", "=", "conn", ".", "cursor", "(", ")", "curs", ".", "executescript", "(", "'''\n DROP TRIGGER container_delete_ps;\n DROP TRIGGER container_insert_ps;\n ALTER TABLE policy_stat\n ADD COLUMN container_count INTEGER DEFAULT 0;\n '''", "+", "POLICY_STAT_TRIGGER_SCRIPT", ")", "# keep the simple case simple, if there's only one entry in the", "# policy_stat table we just copy the total container count from the", "# account_stat table", "# if that triggers an update then the where changes <> 0 *would* exist", "# and the insert or replace from the count subqueries won't execute", "curs", ".", "executescript", "(", "\"\"\"\n UPDATE policy_stat\n SET container_count = (\n SELECT container_count\n FROM account_stat)\n WHERE (\n SELECT COUNT(storage_policy_index)\n FROM policy_stat\n ) <= 1;\n\n INSERT OR REPLACE INTO policy_stat (\n storage_policy_index,\n container_count,\n object_count,\n bytes_used\n )\n SELECT p.storage_policy_index,\n c.count,\n p.object_count,\n p.bytes_used\n FROM (\n SELECT storage_policy_index,\n COUNT(*) as count\n FROM container\n WHERE deleted = 0\n GROUP BY storage_policy_index\n ) c\n JOIN policy_stat p\n ON p.storage_policy_index = c.storage_policy_index\n WHERE NOT EXISTS(\n SELECT changes() as change\n FROM policy_stat\n WHERE change <> 0\n );\n \"\"\"", ")", "conn", ".", "commit", "(", ")" ]
https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/account/backend.py#L551-L609
fluentpython/notebooks
0f6e1e8d1686743dacd9281df7c5b5921812010a
10-seq-hacking/vector_v2.py
python
Vector.__eq__
(self, other)
return tuple(self) == tuple(other)
[]
def __eq__(self, other): return tuple(self) == tuple(other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "tuple", "(", "self", ")", "==", "tuple", "(", "other", ")" ]
https://github.com/fluentpython/notebooks/blob/0f6e1e8d1686743dacd9281df7c5b5921812010a/10-seq-hacking/vector_v2.py#L139-L140
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/categories/pushout.py
python
BlackBoxConstructionFunctor.__ne__
(self, other)
return not (self == other)
Check whether ``self`` is not equal to ``other``. EXAMPLES:: sage: from sage.categories.pushout import BlackBoxConstructionFunctor sage: FG = BlackBoxConstructionFunctor(gap) sage: FM = BlackBoxConstructionFunctor(maxima) sage: FM != FG # indirect doctest True sage: FM != loads(dumps(FM)) False
Check whether ``self`` is not equal to ``other``.
[ "Check", "whether", "self", "is", "not", "equal", "to", "other", "." ]
def __ne__(self, other): """ Check whether ``self`` is not equal to ``other``. EXAMPLES:: sage: from sage.categories.pushout import BlackBoxConstructionFunctor sage: FG = BlackBoxConstructionFunctor(gap) sage: FM = BlackBoxConstructionFunctor(maxima) sage: FM != FG # indirect doctest True sage: FM != loads(dumps(FM)) False """ return not (self == other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "(", "self", "==", "other", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/categories/pushout.py#L3662-L3676
DeepLabCut/DeepLabCut
1dd14c54729ae0d8e66ca495aa5baeb83502e1c7
deeplabcut/gui/labeling_toolbox.py
python
MainFrame.onClick
(self, event)
This function adds labels and auto advances to the next label.
This function adds labels and auto advances to the next label.
[ "This", "function", "adds", "labels", "and", "auto", "advances", "to", "the", "next", "label", "." ]
def onClick(self, event): """ This function adds labels and auto advances to the next label. """ x1 = event.xdata y1 = event.ydata if event.button == 3: if self.rdb.GetSelection() in self.buttonCounter: wx.MessageBox( "%s is already annotated. \n Select another body part to annotate." % (str(self.bodyparts[self.rdb.GetSelection()])), "Error!", wx.OK | wx.ICON_ERROR, ) else: color = self.colormap( self.norm(self.colorIndex[self.rdb.GetSelection()]) ) circle = [ patches.Circle( (x1, y1), radius=self.markerSize, fc=color, alpha=self.alpha ) ] self.num.append(circle) self.axes.add_patch(circle[0]) self.dr = auxfun_drag.DraggablePoint( circle[0], self.bodyparts[self.rdb.GetSelection()] ) self.dr.connect() self.buttonCounter.append(self.rdb.GetSelection()) self.dr.coords = [ [ x1, y1, self.bodyparts[self.rdb.GetSelection()], self.rdb.GetSelection(), ] ] self.drs.append(self.dr) self.updatedCoords.append(self.dr.coords) if self.rdb.GetSelection() < len(self.bodyparts) - 1: self.rdb.SetSelection(self.rdb.GetSelection() + 1) self.figure.canvas.draw() self.canvas.mpl_disconnect(self.onClick) self.canvas.mpl_disconnect(self.onButtonRelease)
[ "def", "onClick", "(", "self", ",", "event", ")", ":", "x1", "=", "event", ".", "xdata", "y1", "=", "event", ".", "ydata", "if", "event", ".", "button", "==", "3", ":", "if", "self", ".", "rdb", ".", "GetSelection", "(", ")", "in", "self", ".", "buttonCounter", ":", "wx", ".", "MessageBox", "(", "\"%s is already annotated. \\n Select another body part to annotate.\"", "%", "(", "str", "(", "self", ".", "bodyparts", "[", "self", ".", "rdb", ".", "GetSelection", "(", ")", "]", ")", ")", ",", "\"Error!\"", ",", "wx", ".", "OK", "|", "wx", ".", "ICON_ERROR", ",", ")", "else", ":", "color", "=", "self", ".", "colormap", "(", "self", ".", "norm", "(", "self", ".", "colorIndex", "[", "self", ".", "rdb", ".", "GetSelection", "(", ")", "]", ")", ")", "circle", "=", "[", "patches", ".", "Circle", "(", "(", "x1", ",", "y1", ")", ",", "radius", "=", "self", ".", "markerSize", ",", "fc", "=", "color", ",", "alpha", "=", "self", ".", "alpha", ")", "]", "self", ".", "num", ".", "append", "(", "circle", ")", "self", ".", "axes", ".", "add_patch", "(", "circle", "[", "0", "]", ")", "self", ".", "dr", "=", "auxfun_drag", ".", "DraggablePoint", "(", "circle", "[", "0", "]", ",", "self", ".", "bodyparts", "[", "self", ".", "rdb", ".", "GetSelection", "(", ")", "]", ")", "self", ".", "dr", ".", "connect", "(", ")", "self", ".", "buttonCounter", ".", "append", "(", "self", ".", "rdb", ".", "GetSelection", "(", ")", ")", "self", ".", "dr", ".", "coords", "=", "[", "[", "x1", ",", "y1", ",", "self", ".", "bodyparts", "[", "self", ".", "rdb", ".", "GetSelection", "(", ")", "]", ",", "self", ".", "rdb", ".", "GetSelection", "(", ")", ",", "]", "]", "self", ".", "drs", ".", "append", "(", "self", ".", "dr", ")", "self", ".", "updatedCoords", ".", "append", "(", "self", ".", "dr", ".", "coords", ")", "if", "self", ".", "rdb", ".", "GetSelection", "(", ")", "<", "len", "(", "self", ".", "bodyparts", ")", "-", "1", ":", "self", ".", "rdb", ".", "SetSelection", "(", "self", ".", "rdb", ".", "GetSelection", "(", ")", "+", "1", ")", "self", ".", "figure", ".", "canvas", ".", "draw", "(", ")", "self", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "onClick", ")", "self", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "onButtonRelease", ")" ]
https://github.com/DeepLabCut/DeepLabCut/blob/1dd14c54729ae0d8e66ca495aa5baeb83502e1c7/deeplabcut/gui/labeling_toolbox.py#L502-L548
TeamMsgExtractor/msg-extractor
8a3a0255a7306bdb8073bd8f222d3be5c688080a
extract_msg/utils.py
python
verifyPropertyId
(id)
Determines whether a property ID is valid for the functions that this function is called from. Property IDs MUST be a 4 digit hexadecimal string.
Determines whether a property ID is valid for the functions that this function is called from. Property IDs MUST be a 4 digit hexadecimal string.
[ "Determines", "whether", "a", "property", "ID", "is", "valid", "for", "the", "functions", "that", "this", "function", "is", "called", "from", ".", "Property", "IDs", "MUST", "be", "a", "4", "digit", "hexadecimal", "string", "." ]
def verifyPropertyId(id): """ Determines whether a property ID is valid for the functions that this function is called from. Property IDs MUST be a 4 digit hexadecimal string. """ if not isinstance(id, str): raise InvaildPropertyIdError('ID was not a 4 digit hexadecimal string') elif len(id) != 4: raise InvaildPropertyIdError('ID was not a 4 digit hexadecimal string') else: try: int(id, 16) except ValueError: raise InvaildPropertyIdError('ID was not a 4 digit hexadecimal string')
[ "def", "verifyPropertyId", "(", "id", ")", ":", "if", "not", "isinstance", "(", "id", ",", "str", ")", ":", "raise", "InvaildPropertyIdError", "(", "'ID was not a 4 digit hexadecimal string'", ")", "elif", "len", "(", "id", ")", "!=", "4", ":", "raise", "InvaildPropertyIdError", "(", "'ID was not a 4 digit hexadecimal string'", ")", "else", ":", "try", ":", "int", "(", "id", ",", "16", ")", "except", "ValueError", ":", "raise", "InvaildPropertyIdError", "(", "'ID was not a 4 digit hexadecimal string'", ")" ]
https://github.com/TeamMsgExtractor/msg-extractor/blob/8a3a0255a7306bdb8073bd8f222d3be5c688080a/extract_msg/utils.py#L585-L598
Teradata/PyTd
5e960ed4c380c4f8ae84d582ad779a87adce5ae1
teradata/pulljson.py
python
JSONPullParser.nextEvent
(self)
Iterator method, return next JSON event from the stream, raises StopIteration() when complete.
Iterator method, return next JSON event from the stream, raises StopIteration() when complete.
[ "Iterator", "method", "return", "next", "JSON", "event", "from", "the", "stream", "raises", "StopIteration", "()", "when", "complete", "." ]
def nextEvent(self): """Iterator method, return next JSON event from the stream, raises StopIteration() when complete.""" try: return self.__next__() except StopIteration: return None
[ "def", "nextEvent", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__next__", "(", ")", "except", "StopIteration", ":", "return", "None" ]
https://github.com/Teradata/PyTd/blob/5e960ed4c380c4f8ae84d582ad779a87adce5ae1/teradata/pulljson.py#L194-L200
ansible/ansible-runner
891a8ad23b01b1d8ed59633a24b6058242614c7e
ansible_runner/cleanup.py
python
prune_images
(runtime='podman')
return True
Run the prune images command and return changed status
Run the prune images command and return changed status
[ "Run", "the", "prune", "images", "command", "and", "return", "changed", "status" ]
def prune_images(runtime='podman'): """Run the prune images command and return changed status""" stdout = run_command([runtime, 'image', 'prune', '-f']) if not stdout or stdout == "Total reclaimed space: 0B": return False return True
[ "def", "prune_images", "(", "runtime", "=", "'podman'", ")", ":", "stdout", "=", "run_command", "(", "[", "runtime", ",", "'image'", ",", "'prune'", ",", "'-f'", "]", ")", "if", "not", "stdout", "or", "stdout", "==", "\"Total reclaimed space: 0B\"", ":", "return", "False", "return", "True" ]
https://github.com/ansible/ansible-runner/blob/891a8ad23b01b1d8ed59633a24b6058242614c7e/ansible_runner/cleanup.py#L159-L164
Theano/Theano
8fd9203edfeecebced9344b0c70193be292a9ade
theano/tensor/nnet/sigm.py
python
is_neg
(var)
return None
Match a variable with the `-x` pattern. Parameters ---------- var The Variable to analyze. Returns ------- object `x` if `var` is of the form `-x`, or None otherwise.
Match a variable with the `-x` pattern.
[ "Match", "a", "variable", "with", "the", "-", "x", "pattern", "." ]
def is_neg(var): """ Match a variable with the `-x` pattern. Parameters ---------- var The Variable to analyze. Returns ------- object `x` if `var` is of the form `-x`, or None otherwise. """ apply = var.owner if not apply: return None # First match against `tensor.neg`. if apply.op == tensor.neg: return apply.inputs[0] # Then match against a multiplication by -1. if apply.op == tensor.mul and len(apply.inputs) >= 2: for idx, mul_input in enumerate(apply.inputs): try: constant = opt.get_scalar_constant_value(mul_input) is_minus_1 = np.allclose(constant, -1) except NotScalarConstantError: is_minus_1 = False if is_minus_1: # Found a multiplication by -1. if len(apply.inputs) == 2: # Only return the other input. return apply.inputs[1 - idx] else: # Return the multiplication of all other inputs. return tensor.mul(*(apply.inputs[0:idx] + apply.inputs[idx + 1:])) # No match. return None
[ "def", "is_neg", "(", "var", ")", ":", "apply", "=", "var", ".", "owner", "if", "not", "apply", ":", "return", "None", "# First match against `tensor.neg`.", "if", "apply", ".", "op", "==", "tensor", ".", "neg", ":", "return", "apply", ".", "inputs", "[", "0", "]", "# Then match against a multiplication by -1.", "if", "apply", ".", "op", "==", "tensor", ".", "mul", "and", "len", "(", "apply", ".", "inputs", ")", ">=", "2", ":", "for", "idx", ",", "mul_input", "in", "enumerate", "(", "apply", ".", "inputs", ")", ":", "try", ":", "constant", "=", "opt", ".", "get_scalar_constant_value", "(", "mul_input", ")", "is_minus_1", "=", "np", ".", "allclose", "(", "constant", ",", "-", "1", ")", "except", "NotScalarConstantError", ":", "is_minus_1", "=", "False", "if", "is_minus_1", ":", "# Found a multiplication by -1.", "if", "len", "(", "apply", ".", "inputs", ")", "==", "2", ":", "# Only return the other input.", "return", "apply", ".", "inputs", "[", "1", "-", "idx", "]", "else", ":", "# Return the multiplication of all other inputs.", "return", "tensor", ".", "mul", "(", "*", "(", "apply", ".", "inputs", "[", "0", ":", "idx", "]", "+", "apply", ".", "inputs", "[", "idx", "+", "1", ":", "]", ")", ")", "# No match.", "return", "None" ]
https://github.com/Theano/Theano/blob/8fd9203edfeecebced9344b0c70193be292a9ade/theano/tensor/nnet/sigm.py#L546-L585
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/decimal.py
python
Decimal.__divmod__
(self, other, context=None)
return quotient, remainder
Return (self // other, self % other)
Return (self // other, self % other)
[ "Return", "(", "self", "//", "other", "self", "%", "other", ")" ]
def __divmod__(self, other, context=None): """ Return (self // other, self % other) """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() ans = self._check_nans(other, context) if ans: return (ans, ans) sign = self._sign ^ other._sign if self._isinfinity(): if other._isinfinity(): ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') return ans, ans else: return (_SignedInfinity[sign], context._raise_error(InvalidOperation, 'INF % x')) if not other: if not self: ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') return ans, ans else: return (context._raise_error(DivisionByZero, 'x // 0', sign), context._raise_error(InvalidOperation, 'x % 0')) quotient, remainder = self._divide(other, context) remainder = remainder._fix(context) return quotient, remainder
[ "def", "__divmod__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "ans", "=", "self", ".", "_check_nans", "(", "other", ",", "context", ")", "if", "ans", ":", "return", "(", "ans", ",", "ans", ")", "sign", "=", "self", ".", "_sign", "^", "other", ".", "_sign", "if", "self", ".", "_isinfinity", "(", ")", ":", "if", "other", ".", "_isinfinity", "(", ")", ":", "ans", "=", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'divmod(INF, INF)'", ")", "return", "ans", ",", "ans", "else", ":", "return", "(", "_SignedInfinity", "[", "sign", "]", ",", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'INF % x'", ")", ")", "if", "not", "other", ":", "if", "not", "self", ":", "ans", "=", "context", ".", "_raise_error", "(", "DivisionUndefined", ",", "'divmod(0, 0)'", ")", "return", "ans", ",", "ans", "else", ":", "return", "(", "context", ".", "_raise_error", "(", "DivisionByZero", ",", "'x // 0'", ",", "sign", ")", ",", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'x % 0'", ")", ")", "quotient", ",", "remainder", "=", "self", ".", "_divide", "(", "other", ",", "context", ")", "remainder", "=", "remainder", ".", "_fix", "(", "context", ")", "return", "quotient", ",", "remainder" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/decimal.py#L1401-L1435
twopirllc/pandas-ta
b92e45c0b8f035ac76292f8f130be32ec49b2ef4
pandas_ta/utils/_core.py
python
is_datetime_ordered
(df: DataFrame or Series)
Returns True if the index is a datetime and ordered.
Returns True if the index is a datetime and ordered.
[ "Returns", "True", "if", "the", "index", "is", "a", "datetime", "and", "ordered", "." ]
def is_datetime_ordered(df: DataFrame or Series) -> bool: """Returns True if the index is a datetime and ordered.""" index_is_datetime = is_datetime64_any_dtype(df.index) try: ordered = df.index[0] < df.index[-1] except RuntimeWarning: pass finally: return True if index_is_datetime and ordered else False
[ "def", "is_datetime_ordered", "(", "df", ":", "DataFrame", "or", "Series", ")", "->", "bool", ":", "index_is_datetime", "=", "is_datetime64_any_dtype", "(", "df", ".", "index", ")", "try", ":", "ordered", "=", "df", ".", "index", "[", "0", "]", "<", "df", ".", "index", "[", "-", "1", "]", "except", "RuntimeWarning", ":", "pass", "finally", ":", "return", "True", "if", "index_is_datetime", "and", "ordered", "else", "False" ]
https://github.com/twopirllc/pandas-ta/blob/b92e45c0b8f035ac76292f8f130be32ec49b2ef4/pandas_ta/utils/_core.py#L37-L45
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/treeview/main.py
python
NodeStyle.__init__
(self, *args, **kargs)
[]
def __init__(self, *args, **kargs): super(NodeStyle, self).__init__(*args, **kargs) self.init()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "super", "(", "NodeStyle", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kargs", ")", "self", ".", "init", "(", ")" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/treeview/main.py#L203-L205
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/images/images_stub.py
python
ImagesServiceStub._Dynamic_Histogram
(self, request, response)
Trivial implementation of ImagesService::Histogram. Based off documentation of the PIL library at http://www.pythonware.com/library/pil/handbook/index.htm Args: request: ImagesHistogramRequest, contains the image. response: ImagesHistogramResponse, contains histogram of the image.
Trivial implementation of ImagesService::Histogram.
[ "Trivial", "implementation", "of", "ImagesService", "::", "Histogram", "." ]
def _Dynamic_Histogram(self, request, response): """Trivial implementation of ImagesService::Histogram. Based off documentation of the PIL library at http://www.pythonware.com/library/pil/handbook/index.htm Args: request: ImagesHistogramRequest, contains the image. response: ImagesHistogramResponse, contains histogram of the image. """ image = self._OpenImageData(request.image()) img_format = image.format if img_format not in ("BMP", "GIF", "ICO", "JPEG", "PNG", "TIFF", "WEBP"): raise apiproxy_errors.ApplicationError( images_service_pb.ImagesServiceError.NOT_IMAGE) image = image.convert("RGBA") red = [0] * 256 green = [0] * 256 blue = [0] * 256 for pixel in image.getdata(): red[int((pixel[0] * pixel[3]) / 255)] += 1 green[int((pixel[1] * pixel[3]) / 255)] += 1 blue[int((pixel[2] * pixel[3]) / 255)] += 1 histogram = response.mutable_histogram() for value in red: histogram.add_red(value) for value in green: histogram.add_green(value) for value in blue: histogram.add_blue(value)
[ "def", "_Dynamic_Histogram", "(", "self", ",", "request", ",", "response", ")", ":", "image", "=", "self", ".", "_OpenImageData", "(", "request", ".", "image", "(", ")", ")", "img_format", "=", "image", ".", "format", "if", "img_format", "not", "in", "(", "\"BMP\"", ",", "\"GIF\"", ",", "\"ICO\"", ",", "\"JPEG\"", ",", "\"PNG\"", ",", "\"TIFF\"", ",", "\"WEBP\"", ")", ":", "raise", "apiproxy_errors", ".", "ApplicationError", "(", "images_service_pb", ".", "ImagesServiceError", ".", "NOT_IMAGE", ")", "image", "=", "image", ".", "convert", "(", "\"RGBA\"", ")", "red", "=", "[", "0", "]", "*", "256", "green", "=", "[", "0", "]", "*", "256", "blue", "=", "[", "0", "]", "*", "256", "for", "pixel", "in", "image", ".", "getdata", "(", ")", ":", "red", "[", "int", "(", "(", "pixel", "[", "0", "]", "*", "pixel", "[", "3", "]", ")", "/", "255", ")", "]", "+=", "1", "green", "[", "int", "(", "(", "pixel", "[", "1", "]", "*", "pixel", "[", "3", "]", ")", "/", "255", ")", "]", "+=", "1", "blue", "[", "int", "(", "(", "pixel", "[", "2", "]", "*", "pixel", "[", "3", "]", ")", "/", "255", ")", "]", "+=", "1", "histogram", "=", "response", ".", "mutable_histogram", "(", ")", "for", "value", "in", "red", ":", "histogram", ".", "add_red", "(", "value", ")", "for", "value", "in", "green", ":", "histogram", ".", "add_green", "(", "value", ")", "for", "value", "in", "blue", ":", "histogram", ".", "add_blue", "(", "value", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/images/images_stub.py#L216-L250
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/domain/decorators.py
python
two_factor_exempt
(view_func)
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
Marks a view function as being exempt from two factor authentication.
Marks a view function as being exempt from two factor authentication.
[ "Marks", "a", "view", "function", "as", "being", "exempt", "from", "two", "factor", "authentication", "." ]
def two_factor_exempt(view_func): """ Marks a view function as being exempt from two factor authentication. """ # We could just do view_func.two_factor_exempt = True, but decorators # are nicer if they don't have side-effects, so we return a new # function. def wrapped_view(*args, **kwargs): return view_func(*args, **kwargs) wrapped_view.two_factor_exempt = True return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
[ "def", "two_factor_exempt", "(", "view_func", ")", ":", "# We could just do view_func.two_factor_exempt = True, but decorators", "# are nicer if they don't have side-effects, so we return a new", "# function.", "def", "wrapped_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "view_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "wrapped_view", ".", "two_factor_exempt", "=", "True", "return", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "(", "wrapped_view", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/domain/decorators.py#L381-L391
omergertel/pyformance
b71056eaf9af6cafd3e3c4a416412ae425bdc82e
example_sysmetrics.py
python
Collector.collect_disk_usage
(self, whitelist=[])
[]
def collect_disk_usage(self, whitelist=[]): for partition in psutil.disk_partitions(): if ( not whitelist or partition.mountpoint in whitelist or partition.device in whitelist ): usage = psutil.disk_usage(partition.mountpoint) if platform.system() == "Windows": disk_name = "-" + partition.mountpoint.replace("\\", "").replace( ":", "" ) else: disk_name = partition.mountpoint.replace("/", "-") if disk_name == "-": disk_name = "-root" self.registry.gauge("df%s.total" % disk_name).set_value(usage.total) self.registry.gauge("df%s.used" % disk_name).set_value(usage.used) self.registry.gauge("df%s.free" % disk_name).set_value(usage.free)
[ "def", "collect_disk_usage", "(", "self", ",", "whitelist", "=", "[", "]", ")", ":", "for", "partition", "in", "psutil", ".", "disk_partitions", "(", ")", ":", "if", "(", "not", "whitelist", "or", "partition", ".", "mountpoint", "in", "whitelist", "or", "partition", ".", "device", "in", "whitelist", ")", ":", "usage", "=", "psutil", ".", "disk_usage", "(", "partition", ".", "mountpoint", ")", "if", "platform", ".", "system", "(", ")", "==", "\"Windows\"", ":", "disk_name", "=", "\"-\"", "+", "partition", ".", "mountpoint", ".", "replace", "(", "\"\\\\\"", ",", "\"\"", ")", ".", "replace", "(", "\":\"", ",", "\"\"", ")", "else", ":", "disk_name", "=", "partition", ".", "mountpoint", ".", "replace", "(", "\"/\"", ",", "\"-\"", ")", "if", "disk_name", "==", "\"-\"", ":", "disk_name", "=", "\"-root\"", "self", ".", "registry", ".", "gauge", "(", "\"df%s.total\"", "%", "disk_name", ")", ".", "set_value", "(", "usage", ".", "total", ")", "self", ".", "registry", ".", "gauge", "(", "\"df%s.used\"", "%", "disk_name", ")", ".", "set_value", "(", "usage", ".", "used", ")", "self", ".", "registry", ".", "gauge", "(", "\"df%s.free\"", "%", "disk_name", ")", ".", "set_value", "(", "usage", ".", "free", ")" ]
https://github.com/omergertel/pyformance/blob/b71056eaf9af6cafd3e3c4a416412ae425bdc82e/example_sysmetrics.py#L59-L77
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/poplib.py
python
POP3.retr
(self, which)
return self._longcmd('RETR %s' % which)
Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets].
Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets].
[ "Retrieve", "whole", "message", "number", "which", ".", "Result", "is", "in", "form", "[", "response", "[", "line", "...", "]", "octets", "]", "." ]
def retr(self, which): """Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets]. """ return self._longcmd('RETR %s' % which)
[ "def", "retr", "(", "self", ",", "which", ")", ":", "return", "self", ".", "_longcmd", "(", "'RETR %s'", "%", "which", ")" ]
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/poplib.py#L179-L184
OpenKMIP/PyKMIP
c0c980395660ea1b1a8009e97f17ab32d1100233
kmip/core/misc.py
python
CertificateValue.__init__
(self, value=b'')
Construct a CertificateValue byte string. Args: value (bytes): A byte string (e.g., b'\x00\x01...') containing the certificate bytes to store. Optional, defaults to the empty byte string.
Construct a CertificateValue byte string.
[ "Construct", "a", "CertificateValue", "byte", "string", "." ]
def __init__(self, value=b''): """ Construct a CertificateValue byte string. Args: value (bytes): A byte string (e.g., b'\x00\x01...') containing the certificate bytes to store. Optional, defaults to the empty byte string. """ super(CertificateValue, self).__init__(value, Tags.CERTIFICATE_VALUE)
[ "def", "__init__", "(", "self", ",", "value", "=", "b''", ")", ":", "super", "(", "CertificateValue", ",", "self", ")", ".", "__init__", "(", "value", ",", "Tags", ".", "CERTIFICATE_VALUE", ")" ]
https://github.com/OpenKMIP/PyKMIP/blob/c0c980395660ea1b1a8009e97f17ab32d1100233/kmip/core/misc.py#L39-L48
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/imaplib.py
python
IMAP4.__getattr__
(self, attr)
[]
def __getattr__(self, attr): # Allow UPPERCASE variants of IMAP4 command methods. if attr in Commands: return getattr(self, attr.lower()) raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "# Allow UPPERCASE variants of IMAP4 command methods.", "if", "attr", "in", "Commands", ":", "return", "getattr", "(", "self", ",", "attr", ".", "lower", "(", ")", ")", "raise", "AttributeError", "(", "\"Unknown IMAP4 command: '%s'\"", "%", "attr", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/imaplib.py#L236-L240
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/sprite.py
python
Sprite.set_hit_box
(self, points: PointList)
Set a sprite's hit box. Hit box should be relative to a sprite's center, and with a scale of 1.0. Points will be scaled with get_adjusted_hit_box.
Set a sprite's hit box. Hit box should be relative to a sprite's center, and with a scale of 1.0. Points will be scaled with get_adjusted_hit_box.
[ "Set", "a", "sprite", "s", "hit", "box", ".", "Hit", "box", "should", "be", "relative", "to", "a", "sprite", "s", "center", "and", "with", "a", "scale", "of", "1", ".", "0", ".", "Points", "will", "be", "scaled", "with", "get_adjusted_hit_box", "." ]
def set_hit_box(self, points: PointList): """ Set a sprite's hit box. Hit box should be relative to a sprite's center, and with a scale of 1.0. Points will be scaled with get_adjusted_hit_box. """ self._point_list_cache = None self._hit_box_shape = None self._points = points
[ "def", "set_hit_box", "(", "self", ",", "points", ":", "PointList", ")", ":", "self", ".", "_point_list_cache", "=", "None", "self", ".", "_hit_box_shape", "=", "None", "self", ".", "_points", "=", "points" ]
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/sprite.py#L345-L353
RDFLib/sparqlwrapper
3fdb48d52bf97c789d121b9650591deba16bcaa6
SPARQLWrapper/sparql_dataframe.py
python
get_sparql_typed_dict
(endpoint, query)
return d
modified from: https://github.com/lawlesst/sparql-dataframe
modified from: https://github.com/lawlesst/sparql-dataframe
[ "modified", "from", ":", "https", ":", "//", "github", ".", "com", "/", "lawlesst", "/", "sparql", "-", "dataframe" ]
def get_sparql_typed_dict(endpoint, query): """ modified from: https://github.com/lawlesst/sparql-dataframe """ # pandas inside to avoid requiring it import pandas as pd # rdflib in here because there is some meta stuff in the setup.py and Travis fails because rdflib is installed later import rdflib.term sparql = SPARQLWrapper2(endpoint) sparql.setQuery(query) if sparql.queryType != SELECT: raise QueryException("Only SPARQL SELECT queries are supported.") # sparql.setReturnFormat(JSON) results = sparql.query() # consider perf hacking later, probably slow # convert list of dicts to python types d = list() for x in results.bindings: row = dict() for k in x: v = x[k] vv = rdflib.term.Literal(v.value, datatype=v.datatype).toPython() row[k] = vv d.append(row) return d
[ "def", "get_sparql_typed_dict", "(", "endpoint", ",", "query", ")", ":", "# pandas inside to avoid requiring it", "import", "pandas", "as", "pd", "# rdflib in here because there is some meta stuff in the setup.py and Travis fails because rdflib is installed later", "import", "rdflib", ".", "term", "sparql", "=", "SPARQLWrapper2", "(", "endpoint", ")", "sparql", ".", "setQuery", "(", "query", ")", "if", "sparql", ".", "queryType", "!=", "SELECT", ":", "raise", "QueryException", "(", "\"Only SPARQL SELECT queries are supported.\"", ")", "# sparql.setReturnFormat(JSON)", "results", "=", "sparql", ".", "query", "(", ")", "# consider perf hacking later, probably slow", "# convert list of dicts to python types", "d", "=", "list", "(", ")", "for", "x", "in", "results", ".", "bindings", ":", "row", "=", "dict", "(", ")", "for", "k", "in", "x", ":", "v", "=", "x", "[", "k", "]", "vv", "=", "rdflib", ".", "term", ".", "Literal", "(", "v", ".", "value", ",", "datatype", "=", "v", ".", "datatype", ")", ".", "toPython", "(", ")", "row", "[", "k", "]", "=", "vv", "d", ".", "append", "(", "row", ")", "return", "d" ]
https://github.com/RDFLib/sparqlwrapper/blob/3fdb48d52bf97c789d121b9650591deba16bcaa6/SPARQLWrapper/sparql_dataframe.py#L22-L44
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
ziplibs/jinja2/lexer.py
python
TokenStream.close
(self)
Close the stream.
Close the stream.
[ "Close", "the", "stream", "." ]
def close(self): """Close the stream.""" self.current = Token(self.current.lineno, TOKEN_EOF, '') self._next = None self.closed = True
[ "def", "close", "(", "self", ")", ":", "self", ".", "current", "=", "Token", "(", "self", ".", "current", ".", "lineno", ",", "TOKEN_EOF", ",", "''", ")", "self", ".", "_next", "=", "None", "self", ".", "closed", "=", "True" ]
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/ziplibs/jinja2/lexer.py#L348-L352
usb-tools/Facedancer
e688fe61dc34087db333432394e1f90e52ac3794
facedancer/future/types.py
python
USBDirection.parse
(cls, value)
return cls(value)
Helper that converts a numeric field into a direction.
Helper that converts a numeric field into a direction.
[ "Helper", "that", "converts", "a", "numeric", "field", "into", "a", "direction", "." ]
def parse(cls, value): """ Helper that converts a numeric field into a direction. """ return cls(value)
[ "def", "parse", "(", "cls", ",", "value", ")", ":", "return", "cls", "(", "value", ")" ]
https://github.com/usb-tools/Facedancer/blob/e688fe61dc34087db333432394e1f90e52ac3794/facedancer/future/types.py#L20-L22
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/modeling/optimization/lr_schedule.py
python
LinearWarmup.__init__
(self, after_warmup_lr_sched: Union[ tf.keras.optimizers.schedules.LearningRateSchedule, float], warmup_steps: int, warmup_learning_rate: float, name: Optional[str] = None)
Add linear warmup schedule to a learning rate schedule. warmup_lr is the initial learning rate, the final learning rate of the init_warmup period is the initial learning rate of lr_schedule in use. The learning rate at each step linearly increased according to the following formula: learning_rate = warmup_lr + step / warmup_steps * (final_warmup_lr - warmup_lr). Using warmup overrides the learning rate schedule by the number of warmup steps. Args: after_warmup_lr_sched: tf.keras.optimizers.schedules .LearningRateSchedule or a constant. warmup_steps: Number of the warmup steps. warmup_learning_rate: Initial learning rate for the warmup. name: Optional, name of warmup schedule.
Add linear warmup schedule to a learning rate schedule.
[ "Add", "linear", "warmup", "schedule", "to", "a", "learning", "rate", "schedule", "." ]
def __init__(self, after_warmup_lr_sched: Union[ tf.keras.optimizers.schedules.LearningRateSchedule, float], warmup_steps: int, warmup_learning_rate: float, name: Optional[str] = None): """Add linear warmup schedule to a learning rate schedule. warmup_lr is the initial learning rate, the final learning rate of the init_warmup period is the initial learning rate of lr_schedule in use. The learning rate at each step linearly increased according to the following formula: learning_rate = warmup_lr + step / warmup_steps * (final_warmup_lr - warmup_lr). Using warmup overrides the learning rate schedule by the number of warmup steps. Args: after_warmup_lr_sched: tf.keras.optimizers.schedules .LearningRateSchedule or a constant. warmup_steps: Number of the warmup steps. warmup_learning_rate: Initial learning rate for the warmup. name: Optional, name of warmup schedule. """ super().__init__() self._name = name self._after_warmup_lr_sched = after_warmup_lr_sched self._warmup_steps = warmup_steps self._init_warmup_lr = warmup_learning_rate if isinstance(after_warmup_lr_sched, tf.keras.optimizers.schedules.LearningRateSchedule): self._final_warmup_lr = after_warmup_lr_sched(warmup_steps) else: self._final_warmup_lr = tf.cast(after_warmup_lr_sched, dtype=tf.float32)
[ "def", "__init__", "(", "self", ",", "after_warmup_lr_sched", ":", "Union", "[", "tf", ".", "keras", ".", "optimizers", ".", "schedules", ".", "LearningRateSchedule", ",", "float", "]", ",", "warmup_steps", ":", "int", ",", "warmup_learning_rate", ":", "float", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "_name", "=", "name", "self", ".", "_after_warmup_lr_sched", "=", "after_warmup_lr_sched", "self", ".", "_warmup_steps", "=", "warmup_steps", "self", ".", "_init_warmup_lr", "=", "warmup_learning_rate", "if", "isinstance", "(", "after_warmup_lr_sched", ",", "tf", ".", "keras", ".", "optimizers", ".", "schedules", ".", "LearningRateSchedule", ")", ":", "self", ".", "_final_warmup_lr", "=", "after_warmup_lr_sched", "(", "warmup_steps", ")", "else", ":", "self", ".", "_final_warmup_lr", "=", "tf", ".", "cast", "(", "after_warmup_lr_sched", ",", "dtype", "=", "tf", ".", "float32", ")" ]
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/modeling/optimization/lr_schedule.py#L95-L128
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/chunk/util.py
python
ChunkScore.missed
(self)
return [c[1] for c in chunks]
Return the chunks which were included in the correct chunk structures, but not in the guessed chunk structures, listed in input order. :rtype: list of chunks
Return the chunks which were included in the correct chunk structures, but not in the guessed chunk structures, listed in input order.
[ "Return", "the", "chunks", "which", "were", "included", "in", "the", "correct", "chunk", "structures", "but", "not", "in", "the", "guessed", "chunk", "structures", "listed", "in", "input", "order", "." ]
def missed(self): """ Return the chunks which were included in the correct chunk structures, but not in the guessed chunk structures, listed in input order. :rtype: list of chunks """ self._updateMeasures() chunks = list(self._fn) return [c[1] for c in chunks]
[ "def", "missed", "(", "self", ")", ":", "self", ".", "_updateMeasures", "(", ")", "chunks", "=", "list", "(", "self", ".", "_fn", ")", "return", "[", "c", "[", "1", "]", "for", "c", "in", "chunks", "]" ]
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/chunk/util.py#L231-L241
lium-lst/nmtpy
dc0a1618f217d5117d6abeacdc15a22443561acf
nmtpy/sysutils.py
python
find_executable
(fname)
Find executable in PATH.
Find executable in PATH.
[ "Find", "executable", "in", "PATH", "." ]
def find_executable(fname): """Find executable in PATH.""" fname = os.path.expanduser(fname) if os.path.isabs(fname) and os.access(fname, os.X_OK): return fname for path in os.environ['PATH'].split(':'): fpath = os.path.join(path, fname) if os.access(fpath, os.X_OK): return fpath
[ "def", "find_executable", "(", "fname", ")", ":", "fname", "=", "os", ".", "path", ".", "expanduser", "(", "fname", ")", "if", "os", ".", "path", ".", "isabs", "(", "fname", ")", "and", "os", ".", "access", "(", "fname", ",", "os", ".", "X_OK", ")", ":", "return", "fname", "for", "path", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "':'", ")", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "fname", ")", "if", "os", ".", "access", "(", "fpath", ",", "os", ".", "X_OK", ")", ":", "return", "fpath" ]
https://github.com/lium-lst/nmtpy/blob/dc0a1618f217d5117d6abeacdc15a22443561acf/nmtpy/sysutils.py#L192-L200
calmevtime/DCTNet
bd7c669b478e47fde230119045133d10e135de97
classification/models/utils.py
python
get_upsample_filter
(size)
return torch.from_numpy(filter).float()
Make a 2D bilinear kernel suitable for upsampling
Make a 2D bilinear kernel suitable for upsampling
[ "Make", "a", "2D", "bilinear", "kernel", "suitable", "for", "upsampling" ]
def get_upsample_filter(size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] filter = (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1] - center) / factor) return torch.from_numpy(filter).float()
[ "def", "get_upsample_filter", "(", "size", ")", ":", "factor", "=", "(", "size", "+", "1", ")", "//", "2", "if", "size", "%", "2", "==", "1", ":", "center", "=", "factor", "-", "1", "else", ":", "center", "=", "factor", "-", "0.5", "og", "=", "np", ".", "ogrid", "[", ":", "size", ",", ":", "size", "]", "filter", "=", "(", "1", "-", "abs", "(", "og", "[", "0", "]", "-", "center", ")", "/", "factor", ")", "*", "(", "1", "-", "abs", "(", "og", "[", "1", "]", "-", "center", ")", "/", "factor", ")", "return", "torch", ".", "from_numpy", "(", "filter", ")", ".", "float", "(", ")" ]
https://github.com/calmevtime/DCTNet/blob/bd7c669b478e47fde230119045133d10e135de97/classification/models/utils.py#L61-L71
bhoov/exbert
d27b6236aa51b185f7d3fed904f25cabe3baeb1a
server/transformers/src/transformers/data/processors/xnli.py
python
XnliProcessor.get_train_examples
(self, data_dir)
return examples
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_train_examples(self, data_dir): """See base class.""" lg = self.language if self.train_language is None else self.train_language lines = self._read_tsv(os.path.join(data_dir, "XNLI-MT-1.0/multinli/multinli.train.{}.tsv".format(lg))) examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % ("train", i) text_a = line[0] text_b = line[1] label = "contradiction" if line[2] == "contradictory" else line[2] assert isinstance(text_a, str) and isinstance(text_b, str) and isinstance(label, str) examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples
[ "def", "get_train_examples", "(", "self", ",", "data_dir", ")", ":", "lg", "=", "self", ".", "language", "if", "self", ".", "train_language", "is", "None", "else", "self", ".", "train_language", "lines", "=", "self", ".", "_read_tsv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"XNLI-MT-1.0/multinli/multinli.train.{}.tsv\"", ".", "format", "(", "lg", ")", ")", ")", "examples", "=", "[", "]", "for", "(", "i", ",", "line", ")", "in", "enumerate", "(", "lines", ")", ":", "if", "i", "==", "0", ":", "continue", "guid", "=", "\"%s-%s\"", "%", "(", "\"train\"", ",", "i", ")", "text_a", "=", "line", "[", "0", "]", "text_b", "=", "line", "[", "1", "]", "label", "=", "\"contradiction\"", "if", "line", "[", "2", "]", "==", "\"contradictory\"", "else", "line", "[", "2", "]", "assert", "isinstance", "(", "text_a", ",", "str", ")", "and", "isinstance", "(", "text_b", ",", "str", ")", "and", "isinstance", "(", "label", ",", "str", ")", "examples", ".", "append", "(", "InputExample", "(", "guid", "=", "guid", ",", "text_a", "=", "text_a", ",", "text_b", "=", "text_b", ",", "label", "=", "label", ")", ")", "return", "examples" ]
https://github.com/bhoov/exbert/blob/d27b6236aa51b185f7d3fed904f25cabe3baeb1a/server/transformers/src/transformers/data/processors/xnli.py#L36-L50
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/cloud/clouds/qingcloud.py
python
show_image
(kwargs, call=None)
return result
Show the details from QingCloud concerning an image. CLI Examples: .. code-block:: bash salt-cloud -f show_image my-qingcloud image=trustysrvx64c salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4 salt-cloud -f show_image my-qingcloud image=trustysrvx64c zone=ap1
Show the details from QingCloud concerning an image.
[ "Show", "the", "details", "from", "QingCloud", "concerning", "an", "image", "." ]
def show_image(kwargs, call=None): """ Show the details from QingCloud concerning an image. CLI Examples: .. code-block:: bash salt-cloud -f show_image my-qingcloud image=trustysrvx64c salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4 salt-cloud -f show_image my-qingcloud image=trustysrvx64c zone=ap1 """ if call != "function": raise SaltCloudSystemExit( "The show_images function must be called with -f or --function" ) if not isinstance(kwargs, dict): kwargs = {} images = kwargs["image"] images = images.split(",") params = { "action": "DescribeImages", "images": images, "zone": _get_specified_zone(kwargs, get_configured_provider()), } items = query(params=params) if not items["image_set"]: raise SaltCloudNotFound("The specified image could not be found.") result = {} for image in items["image_set"]: result[image["image_id"]] = {} for key in image: result[image["image_id"]][key] = image[key] return result
[ "def", "show_image", "(", "kwargs", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "\"function\"", ":", "raise", "SaltCloudSystemExit", "(", "\"The show_images function must be called with -f or --function\"", ")", "if", "not", "isinstance", "(", "kwargs", ",", "dict", ")", ":", "kwargs", "=", "{", "}", "images", "=", "kwargs", "[", "\"image\"", "]", "images", "=", "images", ".", "split", "(", "\",\"", ")", "params", "=", "{", "\"action\"", ":", "\"DescribeImages\"", ",", "\"images\"", ":", "images", ",", "\"zone\"", ":", "_get_specified_zone", "(", "kwargs", ",", "get_configured_provider", "(", ")", ")", ",", "}", "items", "=", "query", "(", "params", "=", "params", ")", "if", "not", "items", "[", "\"image_set\"", "]", ":", "raise", "SaltCloudNotFound", "(", "\"The specified image could not be found.\"", ")", "result", "=", "{", "}", "for", "image", "in", "items", "[", "\"image_set\"", "]", ":", "result", "[", "image", "[", "\"image_id\"", "]", "]", "=", "{", "}", "for", "key", "in", "image", ":", "result", "[", "image", "[", "\"image_id\"", "]", "]", "[", "key", "]", "=", "image", "[", "key", "]", "return", "result" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/qingcloud.py#L328-L368
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/optparse.py
python
OptionGroup.format_help
(self, formatter)
return result
[]
def format_help(self, formatter): result = formatter.format_heading(self.title) formatter.indent() result += OptionContainer.format_help(self, formatter) formatter.dedent() return result
[ "def", "format_help", "(", "self", ",", "formatter", ")", ":", "result", "=", "formatter", ".", "format_heading", "(", "self", ".", "title", ")", "formatter", ".", "indent", "(", ")", "result", "+=", "OptionContainer", ".", "format_help", "(", "self", ",", "formatter", ")", "formatter", ".", "dedent", "(", ")", "return", "result" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/optparse.py#L1098-L1103
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/urllib3/contrib/appengine.py
python
AppEngineManager.urlopen
( self, method, url, body=None, headers=None, retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT, **response_kw )
return http_response
[]
def urlopen( self, method, url, body=None, headers=None, retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT, **response_kw ): retries = self._get_retries(retries, redirect) try: follow_redirects = redirect and retries.redirect != 0 and retries.total response = urlfetch.fetch( url, payload=body, method=method, headers=headers or {}, allow_truncated=False, follow_redirects=self.urlfetch_retries and follow_redirects, deadline=self._get_absolute_timeout(timeout), validate_certificate=self.validate_certificate, ) except urlfetch.DeadlineExceededError as e: raise TimeoutError(self, e) except urlfetch.InvalidURLError as e: if "too large" in str(e): raise AppEnginePlatformError( "URLFetch request too large, URLFetch only " "supports requests up to 10mb in size.", e, ) raise ProtocolError(e) except urlfetch.DownloadError as e: if "Too many redirects" in str(e): raise MaxRetryError(self, url, reason=e) raise ProtocolError(e) except urlfetch.ResponseTooLargeError as e: raise AppEnginePlatformError( "URLFetch response too large, URLFetch only supports" "responses up to 32mb in size.", e, ) except urlfetch.SSLCertificateError as e: raise SSLError(e) except urlfetch.InvalidMethodError as e: raise AppEnginePlatformError( "URLFetch does not support method: %s" % method, e ) http_response = self._urlfetch_response_to_http_response( response, retries=retries, **response_kw ) # Handle redirect? redirect_location = redirect and http_response.get_redirect_location() if redirect_location: # Check for redirect response if self.urlfetch_retries and retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") else: if http_response.status == 303: method = "GET" try: retries = retries.increment( method, url, response=http_response, _pool=self ) except MaxRetryError: if retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") return http_response retries.sleep_for_retry(http_response) log.debug("Redirecting %s -> %s", url, redirect_location) redirect_url = urljoin(url, redirect_location) return self.urlopen( method, redirect_url, body, headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw ) # Check if we should retry the HTTP response. has_retry_after = bool(http_response.getheader("Retry-After")) if retries.is_retry(method, http_response.status, has_retry_after): retries = retries.increment(method, url, response=http_response, _pool=self) log.debug("Retry: %s", url) retries.sleep(http_response) return self.urlopen( method, url, body=body, headers=headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw ) return http_response
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "retries", "=", "None", ",", "redirect", "=", "True", ",", "timeout", "=", "Timeout", ".", "DEFAULT_TIMEOUT", ",", "*", "*", "response_kw", ")", ":", "retries", "=", "self", ".", "_get_retries", "(", "retries", ",", "redirect", ")", "try", ":", "follow_redirects", "=", "redirect", "and", "retries", ".", "redirect", "!=", "0", "and", "retries", ".", "total", "response", "=", "urlfetch", ".", "fetch", "(", "url", ",", "payload", "=", "body", ",", "method", "=", "method", ",", "headers", "=", "headers", "or", "{", "}", ",", "allow_truncated", "=", "False", ",", "follow_redirects", "=", "self", ".", "urlfetch_retries", "and", "follow_redirects", ",", "deadline", "=", "self", ".", "_get_absolute_timeout", "(", "timeout", ")", ",", "validate_certificate", "=", "self", ".", "validate_certificate", ",", ")", "except", "urlfetch", ".", "DeadlineExceededError", "as", "e", ":", "raise", "TimeoutError", "(", "self", ",", "e", ")", "except", "urlfetch", ".", "InvalidURLError", "as", "e", ":", "if", "\"too large\"", "in", "str", "(", "e", ")", ":", "raise", "AppEnginePlatformError", "(", "\"URLFetch request too large, URLFetch only \"", "\"supports requests up to 10mb in size.\"", ",", "e", ",", ")", "raise", "ProtocolError", "(", "e", ")", "except", "urlfetch", ".", "DownloadError", "as", "e", ":", "if", "\"Too many redirects\"", "in", "str", "(", "e", ")", ":", "raise", "MaxRetryError", "(", "self", ",", "url", ",", "reason", "=", "e", ")", "raise", "ProtocolError", "(", "e", ")", "except", "urlfetch", ".", "ResponseTooLargeError", "as", "e", ":", "raise", "AppEnginePlatformError", "(", "\"URLFetch response too large, URLFetch only supports\"", "\"responses up to 32mb in size.\"", ",", "e", ",", ")", "except", "urlfetch", ".", "SSLCertificateError", "as", "e", ":", "raise", "SSLError", "(", "e", ")", "except", "urlfetch", ".", "InvalidMethodError", "as", "e", ":", "raise", "AppEnginePlatformError", "(", "\"URLFetch does not support method: %s\"", "%", "method", ",", "e", ")", "http_response", "=", "self", ".", "_urlfetch_response_to_http_response", "(", "response", ",", "retries", "=", "retries", ",", "*", "*", "response_kw", ")", "# Handle redirect?", "redirect_location", "=", "redirect", "and", "http_response", ".", "get_redirect_location", "(", ")", "if", "redirect_location", ":", "# Check for redirect response", "if", "self", ".", "urlfetch_retries", "and", "retries", ".", "raise_on_redirect", ":", "raise", "MaxRetryError", "(", "self", ",", "url", ",", "\"too many redirects\"", ")", "else", ":", "if", "http_response", ".", "status", "==", "303", ":", "method", "=", "\"GET\"", "try", ":", "retries", "=", "retries", ".", "increment", "(", "method", ",", "url", ",", "response", "=", "http_response", ",", "_pool", "=", "self", ")", "except", "MaxRetryError", ":", "if", "retries", ".", "raise_on_redirect", ":", "raise", "MaxRetryError", "(", "self", ",", "url", ",", "\"too many redirects\"", ")", "return", "http_response", "retries", ".", "sleep_for_retry", "(", "http_response", ")", "log", ".", "debug", "(", "\"Redirecting %s -> %s\"", ",", "url", ",", "redirect_location", ")", "redirect_url", "=", "urljoin", "(", "url", ",", "redirect_location", ")", "return", "self", ".", "urlopen", "(", "method", ",", "redirect_url", ",", "body", ",", "headers", ",", "retries", "=", "retries", ",", "redirect", "=", "redirect", ",", "timeout", "=", "timeout", ",", "*", "*", "response_kw", ")", "# Check if we should retry the HTTP response.", "has_retry_after", "=", "bool", "(", "http_response", ".", "getheader", "(", "\"Retry-After\"", ")", ")", "if", "retries", ".", "is_retry", "(", "method", ",", "http_response", ".", "status", ",", "has_retry_after", ")", ":", "retries", "=", "retries", ".", "increment", "(", "method", ",", "url", ",", "response", "=", "http_response", ",", "_pool", "=", "self", ")", "log", ".", "debug", "(", "\"Retry: %s\"", ",", "url", ")", "retries", ".", "sleep", "(", "http_response", ")", "return", "self", ".", "urlopen", "(", "method", ",", "url", ",", "body", "=", "body", ",", "headers", "=", "headers", ",", "retries", "=", "retries", ",", "redirect", "=", "redirect", ",", "timeout", "=", "timeout", ",", "*", "*", "response_kw", ")", "return", "http_response" ]
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/urllib3/contrib/appengine.py#L131-L243
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/pkg_resources/_vendor/pyparsing.py
python
ParserElement.suppress
( self )
return Suppress( self )
Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output.
Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output.
[ "Suppresses", "the", "output", "of", "this", "C", "{", "ParserElement", "}", ";", "useful", "to", "keep", "punctuation", "from", "cluttering", "up", "returned", "output", "." ]
def suppress( self ): """ Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output. """ return Suppress( self )
[ "def", "suppress", "(", "self", ")", ":", "return", "Suppress", "(", "self", ")" ]
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pkg_resources/_vendor/pyparsing.py#L2045-L2050
GauravBh1010tt/DL-text
eefca341482766e0edbc1bfb6e86ca3399f572c1
dl_text/metrics.py
python
mrr
(out, th = 10)
return MRR * 100.0 / n
[]
def mrr(out, th = 10): n = len(out) MRR = 0.0 for qid in out: candidates = out[qid] for i in xrange(min(th, len(candidates))): if candidates[i] == "true": MRR += 1.0 / (i + 1) break return MRR * 100.0 / n
[ "def", "mrr", "(", "out", ",", "th", "=", "10", ")", ":", "n", "=", "len", "(", "out", ")", "MRR", "=", "0.0", "for", "qid", "in", "out", ":", "candidates", "=", "out", "[", "qid", "]", "for", "i", "in", "xrange", "(", "min", "(", "th", ",", "len", "(", "candidates", ")", ")", ")", ":", "if", "candidates", "[", "i", "]", "==", "\"true\"", ":", "MRR", "+=", "1.0", "/", "(", "i", "+", "1", ")", "break", "return", "MRR", "*", "100.0", "/", "n" ]
https://github.com/GauravBh1010tt/DL-text/blob/eefca341482766e0edbc1bfb6e86ca3399f572c1/dl_text/metrics.py#L16-L25
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/tts/models/degli.py
python
DegliModel.calc_loss
(self, out_blocks: Tensor, y: Tensor, T_ys: Sequence[int])
return loss
calculate L1 loss (criterion) between the real spectrogram and the outputs. Args: out_blocks: output for the Degli model, may include several concatrated outputs. y: desired output. T_ys: lengths (time domain) of non-zero parts of the histrograms, for each sample in the batch. Returns: a loss score.
calculate L1 loss (criterion) between the real spectrogram and the outputs.
[ "calculate", "L1", "loss", "(", "criterion", ")", "between", "the", "real", "spectrogram", "and", "the", "outputs", "." ]
def calc_loss(self, out_blocks: Tensor, y: Tensor, T_ys: Sequence[int]) -> Tensor: """ calculate L1 loss (criterion) between the real spectrogram and the outputs. Args: out_blocks: output for the Degli model, may include several concatrated outputs. y: desired output. T_ys: lengths (time domain) of non-zero parts of the histrograms, for each sample in the batch. Returns: a loss score. """ with warnings.catch_warnings(): warnings.simplefilter('ignore') loss_no_red = self.criterion(out_blocks, y.unsqueeze(1)) loss_blocks = torch.zeros(out_blocks.shape[1], device=y.device) for T, loss_batch in zip(T_ys, loss_no_red): loss_blocks += torch.mean(loss_batch[..., :T], dim=(1, 2, 3)) if len(loss_blocks) == 1: loss = loss_blocks.squeeze() else: loss = loss_blocks @ self.loss_weight return loss
[ "def", "calc_loss", "(", "self", ",", "out_blocks", ":", "Tensor", ",", "y", ":", "Tensor", ",", "T_ys", ":", "Sequence", "[", "int", "]", ")", "->", "Tensor", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "loss_no_red", "=", "self", ".", "criterion", "(", "out_blocks", ",", "y", ".", "unsqueeze", "(", "1", ")", ")", "loss_blocks", "=", "torch", ".", "zeros", "(", "out_blocks", ".", "shape", "[", "1", "]", ",", "device", "=", "y", ".", "device", ")", "for", "T", ",", "loss_batch", "in", "zip", "(", "T_ys", ",", "loss_no_red", ")", ":", "loss_blocks", "+=", "torch", ".", "mean", "(", "loss_batch", "[", "...", ",", ":", "T", "]", ",", "dim", "=", "(", "1", ",", "2", ",", "3", ")", ")", "if", "len", "(", "loss_blocks", ")", "==", "1", ":", "loss", "=", "loss_blocks", ".", "squeeze", "(", ")", "else", ":", "loss", "=", "loss_blocks", "@", "self", ".", "loss_weight", "return", "loss" ]
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/tts/models/degli.py#L199-L222
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/pyasn1/type/tag.py
python
Tag.__getitem__
(self, idx)
[]
def __getitem__(self, idx): if idx == 0: return self.__tagClass elif idx == 1: return self.__tagFormat elif idx == 2: return self.__tagId else: raise IndexError()
[ "def", "__getitem__", "(", "self", ",", "idx", ")", ":", "if", "idx", "==", "0", ":", "return", "self", ".", "__tagClass", "elif", "idx", "==", "1", ":", "return", "self", ".", "__tagFormat", "elif", "idx", "==", "2", ":", "return", "self", ".", "__tagId", "else", ":", "raise", "IndexError", "(", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/pyasn1/type/tag.py#L93-L101
tensorflow/moonlight
b34e8a0106a7d877e4831555be8972a5254f5d96
moonlight/score/elements/key_signature.py
python
KeySignature.try_put
(self, position, accidental)
return can_put
Adds an accidental to the key signature if applicable. Args: position: The accidental glyph y position. accidental: The accidental glyph type. Returns: True if the accidental was successfully added to the key signature. False if the key signature would be invalid when adding the new accidental.
Adds an accidental to the key signature if applicable.
[ "Adds", "an", "accidental", "to", "the", "key", "signature", "if", "applicable", "." ]
def try_put(self, position, accidental): """Adds an accidental to the key signature if applicable. Args: position: The accidental glyph y position. accidental: The accidental glyph type. Returns: True if the accidental was successfully added to the key signature. False if the key signature would be invalid when adding the new accidental. """ can_put = self._can_put(position, accidental) if can_put: self._accidentals[self._normalize_position(position)] = accidental return can_put
[ "def", "try_put", "(", "self", ",", "position", ",", "accidental", ")", ":", "can_put", "=", "self", ".", "_can_put", "(", "position", ",", "accidental", ")", "if", "can_put", ":", "self", ".", "_accidentals", "[", "self", ".", "_normalize_position", "(", "position", ")", "]", "=", "accidental", "return", "can_put" ]
https://github.com/tensorflow/moonlight/blob/b34e8a0106a7d877e4831555be8972a5254f5d96/moonlight/score/elements/key_signature.py#L95-L109
coderholic/pyradio
cd3ee2d6b369fedfd009371a59aca23ab39b020f
pyradio/simple_curses_widgets.py
python
SimpleCursesCheckBox.refresh
(self)
Refresh the widget's content
Refresh the widget's content
[ "Refresh", "the", "widget", "s", "content" ]
def refresh(self): '''Refresh the widget's content''' if self._win: char = self._char if self._checked else ' ' if not self._enabled: try: self._win.addstr(0, 0, '[ ] ', self._bracket_color) self._win.addstr(self._caption, self._bracket_color) except curses.error: pass elif self._focused: if self._highlight_all: try: self._win.addstr(0, 0, '[' + char + '] ' + self._caption, self._color_focused) except curses.error: pass else: try: self._win.addstr(0, 0, '[', self._bracket_color) self._win.addstr(char, self._color_focused) self._win.addstr('] ', self._bracket_color) self._win.addstr(self._caption, self._color) except curses.error: pass else: try: self._win.addstr(0, 0, '[', self._bracket_color) self._win.addstr(char, self._color) self._win.addstr('] ', self._bracket_color) self._win.addstr(self._caption, self._color) except curses.error: pass self._win.touchwin() self._win.refresh()
[ "def", "refresh", "(", "self", ")", ":", "if", "self", ".", "_win", ":", "char", "=", "self", ".", "_char", "if", "self", ".", "_checked", "else", "' '", "if", "not", "self", ".", "_enabled", ":", "try", ":", "self", ".", "_win", ".", "addstr", "(", "0", ",", "0", ",", "'[ ] '", ",", "self", ".", "_bracket_color", ")", "self", ".", "_win", ".", "addstr", "(", "self", ".", "_caption", ",", "self", ".", "_bracket_color", ")", "except", "curses", ".", "error", ":", "pass", "elif", "self", ".", "_focused", ":", "if", "self", ".", "_highlight_all", ":", "try", ":", "self", ".", "_win", ".", "addstr", "(", "0", ",", "0", ",", "'['", "+", "char", "+", "'] '", "+", "self", ".", "_caption", ",", "self", ".", "_color_focused", ")", "except", "curses", ".", "error", ":", "pass", "else", ":", "try", ":", "self", ".", "_win", ".", "addstr", "(", "0", ",", "0", ",", "'['", ",", "self", ".", "_bracket_color", ")", "self", ".", "_win", ".", "addstr", "(", "char", ",", "self", ".", "_color_focused", ")", "self", ".", "_win", ".", "addstr", "(", "'] '", ",", "self", ".", "_bracket_color", ")", "self", ".", "_win", ".", "addstr", "(", "self", ".", "_caption", ",", "self", ".", "_color", ")", "except", "curses", ".", "error", ":", "pass", "else", ":", "try", ":", "self", ".", "_win", ".", "addstr", "(", "0", ",", "0", ",", "'['", ",", "self", ".", "_bracket_color", ")", "self", ".", "_win", ".", "addstr", "(", "char", ",", "self", ".", "_color", ")", "self", ".", "_win", ".", "addstr", "(", "'] '", ",", "self", ".", "_bracket_color", ")", "self", ".", "_win", ".", "addstr", "(", "self", ".", "_caption", ",", "self", ".", "_color", ")", "except", "curses", ".", "error", ":", "pass", "self", ".", "_win", ".", "touchwin", "(", ")", "self", ".", "_win", ".", "refresh", "(", ")" ]
https://github.com/coderholic/pyradio/blob/cd3ee2d6b369fedfd009371a59aca23ab39b020f/pyradio/simple_curses_widgets.py#L1300-L1335
bookwyrm-social/bookwyrm
0c2537e27a2cdbc0136880dfbbf170d5fec72986
bookwyrm/views/inbox.py
python
activity_task
(activity_json)
do something with this json we think is legit
do something with this json we think is legit
[ "do", "something", "with", "this", "json", "we", "think", "is", "legit" ]
def activity_task(activity_json): """do something with this json we think is legit""" # lets see if the activitypub module can make sense of this json activity = activitypub.parse(activity_json) # cool that worked, now we should do the action described by the type # (create, update, delete, etc) activity.action()
[ "def", "activity_task", "(", "activity_json", ")", ":", "# lets see if the activitypub module can make sense of this json", "activity", "=", "activitypub", ".", "parse", "(", "activity_json", ")", "# cool that worked, now we should do the action described by the type", "# (create, update, delete, etc)", "activity", ".", "action", "(", ")" ]
https://github.com/bookwyrm-social/bookwyrm/blob/0c2537e27a2cdbc0136880dfbbf170d5fec72986/bookwyrm/views/inbox.py#L95-L102
Blockstream/satellite
ceb46a00e176c43a6b4170359f6948663a0616bb
blocksatcli/firewall.py
python
_add_iptables_rule
(net_if, cmd)
Add iptables rule Args: net_if : network interface name cmd : list with iptables command
Add iptables rule
[ "Add", "iptables", "rule" ]
def _add_iptables_rule(net_if, cmd): """Add iptables rule Args: net_if : network interface name cmd : list with iptables command """ assert (cmd[0] != "sudo") # Set up the iptables rules runner.run(cmd, root=True) for rule in _get_iptables_rules(net_if): print_rule = False if (rule['rule'][3] == "ACCEPT" and rule['rule'][6] == cmd[6] and rule['rule'][4] == cmd[4]): if (cmd[4] == "igmp"): print_rule = True elif (cmd[4] == "udp" and rule['rule'][12] == cmd[10]): print_rule = True if (print_rule): print("Added iptables rule:\n") print(rule['header1']) print(rule['header2']) print(" ".join(rule['rule']) + "\n")
[ "def", "_add_iptables_rule", "(", "net_if", ",", "cmd", ")", ":", "assert", "(", "cmd", "[", "0", "]", "!=", "\"sudo\"", ")", "# Set up the iptables rules", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ")", "for", "rule", "in", "_get_iptables_rules", "(", "net_if", ")", ":", "print_rule", "=", "False", "if", "(", "rule", "[", "'rule'", "]", "[", "3", "]", "==", "\"ACCEPT\"", "and", "rule", "[", "'rule'", "]", "[", "6", "]", "==", "cmd", "[", "6", "]", "and", "rule", "[", "'rule'", "]", "[", "4", "]", "==", "cmd", "[", "4", "]", ")", ":", "if", "(", "cmd", "[", "4", "]", "==", "\"igmp\"", ")", ":", "print_rule", "=", "True", "elif", "(", "cmd", "[", "4", "]", "==", "\"udp\"", "and", "rule", "[", "'rule'", "]", "[", "12", "]", "==", "cmd", "[", "10", "]", ")", ":", "print_rule", "=", "True", "if", "(", "print_rule", ")", ":", "print", "(", "\"Added iptables rule:\\n\"", ")", "print", "(", "rule", "[", "'header1'", "]", ")", "print", "(", "rule", "[", "'header2'", "]", ")", "print", "(", "\" \"", ".", "join", "(", "rule", "[", "'rule'", "]", ")", "+", "\"\\n\"", ")" ]
https://github.com/Blockstream/satellite/blob/ceb46a00e176c43a6b4170359f6948663a0616bb/blocksatcli/firewall.py#L103-L130
gmr/rabbitpy
d97fd2b1e983df0d95c2b0e2c6b29f61c79d82b9
rabbitpy/io.py
python
IO._socketpair
(self)
return server, client
Return a socket pair regardless of platform. :rtype: (socket.socket, socket.socket)
Return a socket pair regardless of platform.
[ "Return", "a", "socket", "pair", "regardless", "of", "platform", "." ]
def _socketpair(self): """Return a socket pair regardless of platform. :rtype: (socket.socket, socket.socket) """ try: server, client = socket.socketpair() except AttributeError: # Connect in Windows LOGGER.debug('Falling back to emulated socketpair behavior') # Create the listening server socket & bind it to a random port self._server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._server_sock.bind(('127.0.0.1', 0)) # Get the port for the notifying socket to connect to port = self._server_sock.getsockname()[1] # Create the notifying client socket and connect using a timer client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(): """Connect to the client to the server socket pair""" client.connect(('127.0.0.1', port)) timer = threading.Timer(0.01, connect) timer.start() # Have the listening server socket listen and accept the connect self._server_sock.listen(0) # pylint: disable=unused-variable server, _unused = self._server_sock.accept() # Don't block on either socket server.setblocking(0) client.setblocking(0) return server, client
[ "def", "_socketpair", "(", "self", ")", ":", "try", ":", "server", ",", "client", "=", "socket", ".", "socketpair", "(", ")", "except", "AttributeError", ":", "# Connect in Windows", "LOGGER", ".", "debug", "(", "'Falling back to emulated socketpair behavior'", ")", "# Create the listening server socket & bind it to a random port", "self", ".", "_server_sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "_server_sock", ".", "bind", "(", "(", "'127.0.0.1'", ",", "0", ")", ")", "# Get the port for the notifying socket to connect to", "port", "=", "self", ".", "_server_sock", ".", "getsockname", "(", ")", "[", "1", "]", "# Create the notifying client socket and connect using a timer", "client", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "def", "connect", "(", ")", ":", "\"\"\"Connect to the client to the server socket pair\"\"\"", "client", ".", "connect", "(", "(", "'127.0.0.1'", ",", "port", ")", ")", "timer", "=", "threading", ".", "Timer", "(", "0.01", ",", "connect", ")", "timer", ".", "start", "(", ")", "# Have the listening server socket listen and accept the connect", "self", ".", "_server_sock", ".", "listen", "(", "0", ")", "# pylint: disable=unused-variable", "server", ",", "_unused", "=", "self", ".", "_server_sock", ".", "accept", "(", ")", "# Don't block on either socket", "server", ".", "setblocking", "(", "0", ")", "client", ".", "setblocking", "(", "0", ")", "return", "server", ",", "client" ]
https://github.com/gmr/rabbitpy/blob/d97fd2b1e983df0d95c2b0e2c6b29f61c79d82b9/rabbitpy/io.py#L643-L681
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/email/utils.py
python
format_datetime
(dt, usegmt=False)
return _format_timetuple_and_zone(now, zone)
Turn a datetime into a date string as specified in RFC 2822. If usegmt is True, dt must be an aware datetime with an offset of zero. In this case 'GMT' will be rendered instead of the normal +0000 required by RFC2822. This is to support HTTP headers involving date stamps.
Turn a datetime into a date string as specified in RFC 2822.
[ "Turn", "a", "datetime", "into", "a", "date", "string", "as", "specified", "in", "RFC", "2822", "." ]
def format_datetime(dt, usegmt=False): """Turn a datetime into a date string as specified in RFC 2822. If usegmt is True, dt must be an aware datetime with an offset of zero. In this case 'GMT' will be rendered instead of the normal +0000 required by RFC2822. This is to support HTTP headers involving date stamps. """ now = dt.timetuple() if usegmt: if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc: raise ValueError("usegmt option requires a UTC datetime") zone = 'GMT' elif dt.tzinfo is None: zone = '-0000' else: zone = dt.strftime("%z") return _format_timetuple_and_zone(now, zone)
[ "def", "format_datetime", "(", "dt", ",", "usegmt", "=", "False", ")", ":", "now", "=", "dt", ".", "timetuple", "(", ")", "if", "usegmt", ":", "if", "dt", ".", "tzinfo", "is", "None", "or", "dt", ".", "tzinfo", "!=", "datetime", ".", "timezone", ".", "utc", ":", "raise", "ValueError", "(", "\"usegmt option requires a UTC datetime\"", ")", "zone", "=", "'GMT'", "elif", "dt", ".", "tzinfo", "is", "None", ":", "zone", "=", "'-0000'", "else", ":", "zone", "=", "dt", ".", "strftime", "(", "\"%z\"", ")", "return", "_format_timetuple_and_zone", "(", "now", ",", "zone", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/email/utils.py#L167-L183
steeve/xbmctorrent
e6bcb1037668959e1e3cb5ba8cf3e379c6638da9
resources/site-packages/xbmcswift2/listitem.py
python
ListItem.select
(self, selected_status=True)
return self._listitem.select(selected_status)
Sets the listitems selected status to the provided value. Defaults to True.
Sets the listitems selected status to the provided value. Defaults to True.
[ "Sets", "the", "listitems", "selected", "status", "to", "the", "provided", "value", ".", "Defaults", "to", "True", "." ]
def select(self, selected_status=True): '''Sets the listitems selected status to the provided value. Defaults to True. ''' return self._listitem.select(selected_status)
[ "def", "select", "(", "self", ",", "selected_status", "=", "True", ")", ":", "return", "self", ".", "_listitem", ".", "select", "(", "selected_status", ")" ]
https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/xbmcswift2/listitem.py#L91-L95
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/email/_header_value_parser.py
python
get_display_name
(value)
return display_name, value
display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name token with the content of the phrase.
display-name = phrase
[ "display", "-", "name", "=", "phrase" ]
def get_display_name(value): """ display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name token with the content of the phrase. """ display_name = DisplayName() token, value = get_phrase(value) display_name.extend(token[:]) display_name.defects = token.defects[:] return display_name, value
[ "def", "get_display_name", "(", "value", ")", ":", "display_name", "=", "DisplayName", "(", ")", "token", ",", "value", "=", "get_phrase", "(", "value", ")", "display_name", ".", "extend", "(", "token", "[", ":", "]", ")", "display_name", ".", "defects", "=", "token", ".", "defects", "[", ":", "]", "return", "display_name", ",", "value" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/email/_header_value_parser.py#L1722-L1734
daid/LegacyCura
eceece558df51845988bed55a4e667638654f7c4
Cura/util/pymclevel/mce.py
python
mce._relight
(self, command)
relight [ <box> ] Recalculates lights in the region specified. If omitted, recalculates the entire world.
relight [ <box> ]
[ "relight", "[", "<box", ">", "]" ]
def _relight(self, command): """ relight [ <box> ] Recalculates lights in the region specified. If omitted, recalculates the entire world. """ if len(command): box = self.readBox(command) chunks = itertools.product(range(box.mincx, box.maxcx), range(box.mincz, box.maxcz)) else: chunks = self.level.allChunks self.level.generateLights(chunks) print "Relit 0 chunks." self.needsSave = True
[ "def", "_relight", "(", "self", ",", "command", ")", ":", "if", "len", "(", "command", ")", ":", "box", "=", "self", ".", "readBox", "(", "command", ")", "chunks", "=", "itertools", ".", "product", "(", "range", "(", "box", ".", "mincx", ",", "box", ".", "maxcx", ")", ",", "range", "(", "box", ".", "mincz", ",", "box", ".", "maxcz", ")", ")", "else", ":", "chunks", "=", "self", ".", "level", ".", "allChunks", "self", ".", "level", ".", "generateLights", "(", "chunks", ")", "print", "\"Relit 0 chunks.\"", "self", ".", "needsSave", "=", "True" ]
https://github.com/daid/LegacyCura/blob/eceece558df51845988bed55a4e667638654f7c4/Cura/util/pymclevel/mce.py#L944-L961
reiinakano/scikit-plot
2dd3e6a76df77edcbd724c4db25575f70abb57cb
scikitplot/cluster.py
python
_clone_and_score_clusterer
(clf, X, n_clusters)
return clf.fit(X).score(X), time.time() - start
Clones and scores clusterer instance. Args: clf: Clusterer instance that implements ``fit``,``fit_predict``, and ``score`` methods, and an ``n_clusters`` hyperparameter. e.g. :class:`sklearn.cluster.KMeans` instance X (array-like, shape (n_samples, n_features)): Data to cluster, where n_samples is the number of samples and n_features is the number of features. n_clusters (int): Number of clusters Returns: score: Score of clusters time: Number of seconds it took to fit cluster
Clones and scores clusterer instance.
[ "Clones", "and", "scores", "clusterer", "instance", "." ]
def _clone_and_score_clusterer(clf, X, n_clusters): """Clones and scores clusterer instance. Args: clf: Clusterer instance that implements ``fit``,``fit_predict``, and ``score`` methods, and an ``n_clusters`` hyperparameter. e.g. :class:`sklearn.cluster.KMeans` instance X (array-like, shape (n_samples, n_features)): Data to cluster, where n_samples is the number of samples and n_features is the number of features. n_clusters (int): Number of clusters Returns: score: Score of clusters time: Number of seconds it took to fit cluster """ start = time.time() clf = clone(clf) setattr(clf, 'n_clusters', n_clusters) return clf.fit(X).score(X), time.time() - start
[ "def", "_clone_and_score_clusterer", "(", "clf", ",", "X", ",", "n_clusters", ")", ":", "start", "=", "time", ".", "time", "(", ")", "clf", "=", "clone", "(", "clf", ")", "setattr", "(", "clf", ",", "'n_clusters'", ",", "n_clusters", ")", "return", "clf", ".", "fit", "(", "X", ")", ".", "score", "(", "X", ")", ",", "time", ".", "time", "(", ")", "-", "start" ]
https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/cluster.py#L110-L132
pritunl/pritunl
d793ce820f53f31bfc01e86d8b92ec098ab6362d
pritunl/utils/none_queue.py
python
NoneQueue.qsize
(self)
return n
Return the approximate size of the queue (not reliable!).
Return the approximate size of the queue (not reliable!).
[ "Return", "the", "approximate", "size", "of", "the", "queue", "(", "not", "reliable!", ")", "." ]
def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() n = self._qsize() self.mutex.release() return n
[ "def", "qsize", "(", "self", ")", ":", "self", ".", "mutex", ".", "acquire", "(", ")", "n", "=", "self", ".", "_qsize", "(", ")", "self", ".", "mutex", ".", "release", "(", ")", "return", "n" ]
https://github.com/pritunl/pritunl/blob/d793ce820f53f31bfc01e86d8b92ec098ab6362d/pritunl/utils/none_queue.py#L73-L78
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/gzip.py
python
GzipFile.fileno
(self)
return self.fileobj.fileno()
Invoke the underlying file object's fileno() method. This will raise AttributeError if the underlying file object doesn't support fileno().
Invoke the underlying file object's fileno() method.
[ "Invoke", "the", "underlying", "file", "object", "s", "fileno", "()", "method", "." ]
def fileno(self): """Invoke the underlying file object's fileno() method. This will raise AttributeError if the underlying file object doesn't support fileno(). """ return self.fileobj.fileno()
[ "def", "fileno", "(", "self", ")", ":", "return", "self", ".", "fileobj", ".", "fileno", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/gzip.py#L393-L399
DeepLabCut/DeepLabCut
1dd14c54729ae0d8e66ca495aa5baeb83502e1c7
deeplabcut/pose_estimation_tensorflow/backbones/efficientnet_builder.py
python
build_model_base
( images, model_name, use_batch_norm=False, drop_out=False, override_params=None )
return features, model.endpoints
A helper functiion to create a base model and return global_pool. Args: images: input images tensor. model_name: string, the predefined model name. training: boolean, whether the model is constructed for training. override_params: A dictionary of params for overriding. Fields must exist in efficientnet_model.GlobalParams. Returns: features: global pool features. endpoints: the endpoints for each layer. Raises: When model_name specified an undefined model, raises NotImplementedError. When override_params has invalid fields, raises ValueError.
A helper functiion to create a base model and return global_pool. Args: images: input images tensor. model_name: string, the predefined model name. training: boolean, whether the model is constructed for training. override_params: A dictionary of params for overriding. Fields must exist in efficientnet_model.GlobalParams. Returns: features: global pool features. endpoints: the endpoints for each layer. Raises: When model_name specified an undefined model, raises NotImplementedError. When override_params has invalid fields, raises ValueError.
[ "A", "helper", "functiion", "to", "create", "a", "base", "model", "and", "return", "global_pool", ".", "Args", ":", "images", ":", "input", "images", "tensor", ".", "model_name", ":", "string", "the", "predefined", "model", "name", ".", "training", ":", "boolean", "whether", "the", "model", "is", "constructed", "for", "training", ".", "override_params", ":", "A", "dictionary", "of", "params", "for", "overriding", ".", "Fields", "must", "exist", "in", "efficientnet_model", ".", "GlobalParams", ".", "Returns", ":", "features", ":", "global", "pool", "features", ".", "endpoints", ":", "the", "endpoints", "for", "each", "layer", ".", "Raises", ":", "When", "model_name", "specified", "an", "undefined", "model", "raises", "NotImplementedError", ".", "When", "override_params", "has", "invalid", "fields", "raises", "ValueError", "." ]
def build_model_base( images, model_name, use_batch_norm=False, drop_out=False, override_params=None ): """A helper functiion to create a base model and return global_pool. Args: images: input images tensor. model_name: string, the predefined model name. training: boolean, whether the model is constructed for training. override_params: A dictionary of params for overriding. Fields must exist in efficientnet_model.GlobalParams. Returns: features: global pool features. endpoints: the endpoints for each layer. Raises: When model_name specified an undefined model, raises NotImplementedError. When override_params has invalid fields, raises ValueError. """ assert isinstance(images, tf.Tensor) blocks_args, global_params = get_model_params(model_name, override_params) with tf.compat.v1.variable_scope(model_name): model = efficientnet_model.Model(blocks_args, global_params) features = model( images, use_batch_norm=use_batch_norm, drop_out=drop_out, features_only=True ) features = tf.identity(features, "features") return features, model.endpoints
[ "def", "build_model_base", "(", "images", ",", "model_name", ",", "use_batch_norm", "=", "False", ",", "drop_out", "=", "False", ",", "override_params", "=", "None", ")", ":", "assert", "isinstance", "(", "images", ",", "tf", ".", "Tensor", ")", "blocks_args", ",", "global_params", "=", "get_model_params", "(", "model_name", ",", "override_params", ")", "with", "tf", ".", "compat", ".", "v1", ".", "variable_scope", "(", "model_name", ")", ":", "model", "=", "efficientnet_model", ".", "Model", "(", "blocks_args", ",", "global_params", ")", "features", "=", "model", "(", "images", ",", "use_batch_norm", "=", "use_batch_norm", ",", "drop_out", "=", "drop_out", ",", "features_only", "=", "True", ")", "features", "=", "tf", ".", "identity", "(", "features", ",", "\"features\"", ")", "return", "features", ",", "model", ".", "endpoints" ]
https://github.com/DeepLabCut/DeepLabCut/blob/1dd14c54729ae0d8e66ca495aa5baeb83502e1c7/deeplabcut/pose_estimation_tensorflow/backbones/efficientnet_builder.py#L256-L283
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/webapp2-2.5.2/webapp2_extras/i18n.py
python
I18n.format_percent
(self, number, format=None)
return numbers.format_percent(number, format=format, locale=self.locale)
Returns formatted percent value for the current locale. Example:: >>> format_percent(0.34, locale='en_US') u'34%' >>> format_percent(25.1234, locale='en_US') u'2,512%' >>> format_percent(25.1234, locale='sv_SE') u'2\\xa0512\\xa0%' The format pattern can also be specified explicitly:: >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US') u'25,123\u2030' :param number: The percent number to format :param format: Notation format. :returns: The formatted percent number.
Returns formatted percent value for the current locale. Example::
[ "Returns", "formatted", "percent", "value", "for", "the", "current", "locale", ".", "Example", "::" ]
def format_percent(self, number, format=None): """Returns formatted percent value for the current locale. Example:: >>> format_percent(0.34, locale='en_US') u'34%' >>> format_percent(25.1234, locale='en_US') u'2,512%' >>> format_percent(25.1234, locale='sv_SE') u'2\\xa0512\\xa0%' The format pattern can also be specified explicitly:: >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US') u'25,123\u2030' :param number: The percent number to format :param format: Notation format. :returns: The formatted percent number. """ return numbers.format_percent(number, format=format, locale=self.locale)
[ "def", "format_percent", "(", "self", ",", "number", ",", "format", "=", "None", ")", ":", "return", "numbers", ".", "format_percent", "(", "number", ",", "format", "=", "format", ",", "locale", "=", "self", ".", "locale", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/webapp2-2.5.2/webapp2_extras/i18n.py#L534-L557
espeed/bulbs
628e5b14f0249f9ca4fa1ceea6f2af2dca45f75a
bulbs/neo4jserver/client.py
python
Neo4jClient.delete_vertex
(self, _id)
return self.gremlin(script,params)
Deletes a vertex with the _id and returns the Response. :param _id: Vertex ID. :type _id: dict :rtype: Neo4jResponse
Deletes a vertex with the _id and returns the Response.
[ "Deletes", "a", "vertex", "with", "the", "_id", "and", "returns", "the", "Response", "." ]
def delete_vertex(self, _id): """ Deletes a vertex with the _id and returns the Response. :param _id: Vertex ID. :type _id: dict :rtype: Neo4jResponse """ script = self.scripts.get("delete_vertex") params = dict(_id=_id) return self.gremlin(script,params)
[ "def", "delete_vertex", "(", "self", ",", "_id", ")", ":", "script", "=", "self", ".", "scripts", ".", "get", "(", "\"delete_vertex\"", ")", "params", "=", "dict", "(", "_id", "=", "_id", ")", "return", "self", ".", "gremlin", "(", "script", ",", "params", ")" ]
https://github.com/espeed/bulbs/blob/628e5b14f0249f9ca4fa1ceea6f2af2dca45f75a/bulbs/neo4jserver/client.py#L474-L486
jamesturk/validictory
6571d051014a3fc302ecd8d67191cd07a6973fdd
validictory/validator.py
python
SchemaValidator.validate_items
(self, x, fieldname, schema, path, items=None)
Validates that all items in the list for the given field match the given schema
Validates that all items in the list for the given field match the given schema
[ "Validates", "that", "all", "items", "in", "the", "list", "for", "the", "given", "field", "match", "the", "given", "schema" ]
def validate_items(self, x, fieldname, schema, path, items=None): ''' Validates that all items in the list for the given field match the given schema ''' if x.get(fieldname) is not None: value = x.get(fieldname) if isinstance(value, (list, tuple)): if isinstance(items, (list, tuple)): if 'additionalItems' not in schema and len(items) != len(value): self._error("is not of same length as schema list", value, fieldname, path=path) else: for index, item in enumerate(items): try: self.__validate("_data", {"_data": value[index]}, item, '{0}[{1}]'.format(path, index)) except FieldValidationError as e: raise type(e)("Failed to validate field '%s' list schema: %s" % (fieldname, e), fieldname, e.value) elif isinstance(items, dict): for index, item in enumerate(value): if ((self.disallow_unknown_properties or self.remove_unknown_properties) and 'properties' in items): self._validate_unknown_properties(items['properties'], item, fieldname, schema.get('patternProperties')) self.__validate("[list item]", {"[list item]": item}, items, '{0}[{1}]'.format(path, index)) else: raise SchemaError("Properties definition of field '{0}' is " "not a list or an object".format(fieldname))
[ "def", "validate_items", "(", "self", ",", "x", ",", "fieldname", ",", "schema", ",", "path", ",", "items", "=", "None", ")", ":", "if", "x", ".", "get", "(", "fieldname", ")", "is", "not", "None", ":", "value", "=", "x", ".", "get", "(", "fieldname", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "isinstance", "(", "items", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "'additionalItems'", "not", "in", "schema", "and", "len", "(", "items", ")", "!=", "len", "(", "value", ")", ":", "self", ".", "_error", "(", "\"is not of same length as schema list\"", ",", "value", ",", "fieldname", ",", "path", "=", "path", ")", "else", ":", "for", "index", ",", "item", "in", "enumerate", "(", "items", ")", ":", "try", ":", "self", ".", "__validate", "(", "\"_data\"", ",", "{", "\"_data\"", ":", "value", "[", "index", "]", "}", ",", "item", ",", "'{0}[{1}]'", ".", "format", "(", "path", ",", "index", ")", ")", "except", "FieldValidationError", "as", "e", ":", "raise", "type", "(", "e", ")", "(", "\"Failed to validate field '%s' list schema: %s\"", "%", "(", "fieldname", ",", "e", ")", ",", "fieldname", ",", "e", ".", "value", ")", "elif", "isinstance", "(", "items", ",", "dict", ")", ":", "for", "index", ",", "item", "in", "enumerate", "(", "value", ")", ":", "if", "(", "(", "self", ".", "disallow_unknown_properties", "or", "self", ".", "remove_unknown_properties", ")", "and", "'properties'", "in", "items", ")", ":", "self", ".", "_validate_unknown_properties", "(", "items", "[", "'properties'", "]", ",", "item", ",", "fieldname", ",", "schema", ".", "get", "(", "'patternProperties'", ")", ")", "self", ".", "__validate", "(", "\"[list item]\"", ",", "{", "\"[list item]\"", ":", "item", "}", ",", "items", ",", "'{0}[{1}]'", ".", "format", "(", "path", ",", "index", ")", ")", "else", ":", "raise", "SchemaError", "(", "\"Properties definition of field '{0}' is \"", "\"not a list or an object\"", ".", "format", "(", "fieldname", ")", ")" ]
https://github.com/jamesturk/validictory/blob/6571d051014a3fc302ecd8d67191cd07a6973fdd/validictory/validator.py#L298-L330
deepmind/dm_control
806a10e896e7c887635328bfa8352604ad0fedae
dm_control/composer/observation/observable/base.py
python
Observable.update_interval
(self)
return self._update_interval
[]
def update_interval(self): return self._update_interval
[ "def", "update_interval", "(", "self", ")", ":", "return", "self", ".", "_update_interval" ]
https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/composer/observation/observable/base.py#L67-L68
medipixel/rl_algorithms
c5f7d1d60dcefb3050d75c5c657207183bd8db65
rl_algorithms/dqn/linear.py
python
NoisyLinear.__init__
(self, in_features: int, out_features: int, std_init: float = 0.5)
Initialize.
Initialize.
[ "Initialize", "." ]
def __init__(self, in_features: int, out_features: int, std_init: float = 0.5): """Initialize.""" super(NoisyLinear, self).__init__() self.in_features = in_features self.out_features = out_features self.std_init = std_init self.weight_mu = nn.Parameter(torch.Tensor(out_features, in_features)) self.weight_sigma = nn.Parameter(torch.Tensor(out_features, in_features)) self.register_buffer("weight_epsilon", torch.Tensor(out_features, in_features)) self.bias_mu = nn.Parameter(torch.Tensor(out_features)) self.bias_sigma = nn.Parameter(torch.Tensor(out_features)) self.register_buffer("bias_epsilon", torch.Tensor(out_features)) self.reset_parameters() self.reset_noise()
[ "def", "__init__", "(", "self", ",", "in_features", ":", "int", ",", "out_features", ":", "int", ",", "std_init", ":", "float", "=", "0.5", ")", ":", "super", "(", "NoisyLinear", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "in_features", "=", "in_features", "self", ".", "out_features", "=", "out_features", "self", ".", "std_init", "=", "std_init", "self", ".", "weight_mu", "=", "nn", ".", "Parameter", "(", "torch", ".", "Tensor", "(", "out_features", ",", "in_features", ")", ")", "self", ".", "weight_sigma", "=", "nn", ".", "Parameter", "(", "torch", ".", "Tensor", "(", "out_features", ",", "in_features", ")", ")", "self", ".", "register_buffer", "(", "\"weight_epsilon\"", ",", "torch", ".", "Tensor", "(", "out_features", ",", "in_features", ")", ")", "self", ".", "bias_mu", "=", "nn", ".", "Parameter", "(", "torch", ".", "Tensor", "(", "out_features", ")", ")", "self", ".", "bias_sigma", "=", "nn", ".", "Parameter", "(", "torch", ".", "Tensor", "(", "out_features", ")", ")", "self", ".", "register_buffer", "(", "\"bias_epsilon\"", ",", "torch", ".", "Tensor", "(", "out_features", ")", ")", "self", ".", "reset_parameters", "(", ")", "self", ".", "reset_noise", "(", ")" ]
https://github.com/medipixel/rl_algorithms/blob/c5f7d1d60dcefb3050d75c5c657207183bd8db65/rl_algorithms/dqn/linear.py#L40-L56
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/iam/connection.py
python
IAMConnection.detach_group_policy
(self, policy_arn, group_name)
return self.get_response('DetachGroupPolicy', params)
:type policy_arn: string :param policy_arn: The ARN of the policy to detach :type group_name: string :param group_name: Group to detach the policy from
:type policy_arn: string :param policy_arn: The ARN of the policy to detach
[ ":", "type", "policy_arn", ":", "string", ":", "param", "policy_arn", ":", "The", "ARN", "of", "the", "policy", "to", "detach" ]
def detach_group_policy(self, policy_arn, group_name): """ :type policy_arn: string :param policy_arn: The ARN of the policy to detach :type group_name: string :param group_name: Group to detach the policy from """ params = {'PolicyArn': policy_arn, 'GroupName': group_name} return self.get_response('DetachGroupPolicy', params)
[ "def", "detach_group_policy", "(", "self", ",", "policy_arn", ",", "group_name", ")", ":", "params", "=", "{", "'PolicyArn'", ":", "policy_arn", ",", "'GroupName'", ":", "group_name", "}", "return", "self", ".", "get_response", "(", "'DetachGroupPolicy'", ",", "params", ")" ]
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/iam/connection.py#L1898-L1908
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/setuptools/windows_support.py
python
windows_only
(func)
return func
[]
def windows_only(func): if platform.system() != 'Windows': return lambda *args, **kwargs: None return func
[ "def", "windows_only", "(", "func", ")", ":", "if", "platform", ".", "system", "(", ")", "!=", "'Windows'", ":", "return", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "None", "return", "func" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/setuptools/windows_support.py#L5-L8
pyhys/minimalmodbus
185afffd2d65b585f69bc5e3f640270d2bd27444
minimalmodbus.py
python
_hexdecode
(hexstring: str)
r"""Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\x04'`` (which has length 1). Args: * hexstring: Can be for example 'A3' or 'A3B4'. Must be of even length. * Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space). Returns: A string of half the length, with characters corresponding to all 0-255 values for each byte. Raises: TypeError, ValueError
r"""Convert a hex encoded string to a byte string.
[ "r", "Convert", "a", "hex", "encoded", "string", "to", "a", "byte", "string", "." ]
def _hexdecode(hexstring: str) -> str: r"""Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\x04'`` (which has length 1). Args: * hexstring: Can be for example 'A3' or 'A3B4'. Must be of even length. * Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space). Returns: A string of half the length, with characters corresponding to all 0-255 values for each byte. Raises: TypeError, ValueError """ # Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err # but the Python2 interpreter will indicate SyntaxError. # Thus we need to live with this warning in Python3: # 'During handling of the above exception, another exception occurred' _check_string(hexstring, description="hexstring") if len(hexstring) % 2 != 0: raise ValueError( "The input hexstring must be of even length. Given: {!r}".format(hexstring) ) converted_bytes = bytes(hexstring, "latin1") try: return str(binascii.unhexlify(converted_bytes), encoding="latin1") except binascii.Error as err: new_error_message = ( "Hexdecode reported an error: {!s}. Input hexstring: {}".format( err.args[0], hexstring ) ) raise TypeError(new_error_message)
[ "def", "_hexdecode", "(", "hexstring", ":", "str", ")", "->", "str", ":", "# Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err", "# but the Python2 interpreter will indicate SyntaxError.", "# Thus we need to live with this warning in Python3:", "# 'During handling of the above exception, another exception occurred'", "_check_string", "(", "hexstring", ",", "description", "=", "\"hexstring\"", ")", "if", "len", "(", "hexstring", ")", "%", "2", "!=", "0", ":", "raise", "ValueError", "(", "\"The input hexstring must be of even length. Given: {!r}\"", ".", "format", "(", "hexstring", ")", ")", "converted_bytes", "=", "bytes", "(", "hexstring", ",", "\"latin1\"", ")", "try", ":", "return", "str", "(", "binascii", ".", "unhexlify", "(", "converted_bytes", ")", ",", "encoding", "=", "\"latin1\"", ")", "except", "binascii", ".", "Error", "as", "err", ":", "new_error_message", "=", "(", "\"Hexdecode reported an error: {!s}. Input hexstring: {}\"", ".", "format", "(", "err", ".", "args", "[", "0", "]", ",", "hexstring", ")", ")", "raise", "TypeError", "(", "new_error_message", ")" ]
https://github.com/pyhys/minimalmodbus/blob/185afffd2d65b585f69bc5e3f640270d2bd27444/minimalmodbus.py#L2673-L2712