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
pygae/clifford
0b6cffb9a6d44ecb7a666f6b08b1788fc94a0ab6
clifford/tools/g3c/rotor_parameterisation.py
python
interpolate_TR_rotors
(R_n_plus_1, R_n, interpolation_fraction)
return R_n_lambda
Interpolates TR type rotors From :cite:`wareham-interpolation`.
Interpolates TR type rotors
[ "Interpolates", "TR", "type", "rotors" ]
def interpolate_TR_rotors(R_n_plus_1, R_n, interpolation_fraction): """ Interpolates TR type rotors From :cite:`wareham-interpolation`. """ if interpolation_fraction < np.finfo(float).eps: return R_n delta_R = R_n_plus_1 * ~R_n delta_bivector = ga_log(delta_R)(2) R_n_lambda = ga_exp(interpolation_fraction * delta_bivector) * R_n return R_n_lambda
[ "def", "interpolate_TR_rotors", "(", "R_n_plus_1", ",", "R_n", ",", "interpolation_fraction", ")", ":", "if", "interpolation_fraction", "<", "np", ".", "finfo", "(", "float", ")", ".", "eps", ":", "return", "R_n", "delta_R", "=", "R_n_plus_1", "*", "~", "R_n...
https://github.com/pygae/clifford/blob/0b6cffb9a6d44ecb7a666f6b08b1788fc94a0ab6/clifford/tools/g3c/rotor_parameterisation.py#L196-L207
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/pydoc.py
python
resolve
(thing, forceload=0)
Given an object or a path to an object, get the object and its name.
Given an object or a path to an object, get the object and its name.
[ "Given", "an", "object", "or", "a", "path", "to", "an", "object", "get", "the", "object", "and", "its", "name", "." ]
def resolve(thing, forceload=0): """Given an object or a path to an object, get the object and its name.""" if isinstance(thing, str): object = locate(thing, forceload) if object is None: raise ImportError('no Python documentation found for %r' % thing) return object, thing else: name = getattr(thing, '__name__', None) return thing, name if isinstance(name, str) else None
[ "def", "resolve", "(", "thing", ",", "forceload", "=", "0", ")", ":", "if", "isinstance", "(", "thing", ",", "str", ")", ":", "object", "=", "locate", "(", "thing", ",", "forceload", ")", "if", "object", "is", "None", ":", "raise", "ImportError", "("...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/pydoc.py#L1589-L1598
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
13-protocol-abc/tombola_subhook.py
python
Tombola.pick
(self)
Remove item at random, returning it. This method should raise `LookupError` when the instance is empty.
Remove item at random, returning it.
[ "Remove", "item", "at", "random", "returning", "it", "." ]
def pick(self): # <3> """Remove item at random, returning it. This method should raise `LookupError` when the instance is empty. """
[ "def", "pick", "(", "self", ")", ":", "# <3>" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/13-protocol-abc/tombola_subhook.py#L36-L40
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/MicrosoftGraphApplications/Integrations/MicrosoftGraphApplications/MicrosoftGraphApplications.py
python
Client.delete_service_principals
( self, service_id: str )
Deletes a given id from authorized apps. Arguments: service_id: the service to remove Returns: True if removed successfully Raises: DemistoException if no app exists or any other requests error. Docs: https://docs.microsoft.com/en-us/graph/api/serviceprincipal-delete?view=graph-rest-1.0&tabs=http
Deletes a given id from authorized apps.
[ "Deletes", "a", "given", "id", "from", "authorized", "apps", "." ]
def delete_service_principals( self, service_id: str ): """Deletes a given id from authorized apps. Arguments: service_id: the service to remove Returns: True if removed successfully Raises: DemistoException if no app exists or any other requests error. Docs: https://docs.microsoft.com/en-us/graph/api/serviceprincipal-delete?view=graph-rest-1.0&tabs=http """ self.ms_client.http_request( 'DELETE', f'v1.0/servicePrincipals/{service_id}', return_empty_response=True )
[ "def", "delete_service_principals", "(", "self", ",", "service_id", ":", "str", ")", ":", "self", ".", "ms_client", ".", "http_request", "(", "'DELETE'", ",", "f'v1.0/servicePrincipals/{service_id}'", ",", "return_empty_response", "=", "True", ")" ]
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/MicrosoftGraphApplications/Integrations/MicrosoftGraphApplications/MicrosoftGraphApplications.py#L69-L89
cenkalti/kuyruk
1052334e804c137245ddbbed31c75fa0aac46a71
kuyruk/worker.py
python
Worker._handle_sigusr2
(self, signum: int, frame: Any)
Drop current task.
Drop current task.
[ "Drop", "current", "task", "." ]
def _handle_sigusr2(self, signum: int, frame: Any) -> None: """Drop current task.""" logger.warning("Catched SIGUSR2") if self.current_task: logger.warning("Dropping current task...") raise Discard
[ "def", "_handle_sigusr2", "(", "self", ",", "signum", ":", "int", ",", "frame", ":", "Any", ")", "->", "None", ":", "logger", ".", "warning", "(", "\"Catched SIGUSR2\"", ")", "if", "self", ".", "current_task", ":", "logger", ".", "warning", "(", "\"Dropp...
https://github.com/cenkalti/kuyruk/blob/1052334e804c137245ddbbed31c75fa0aac46a71/kuyruk/worker.py#L405-L410
quantopian/trading_calendars
19c4b677f13147928d34be5a3da50ba4161be45d
trading_calendars/calendar_utils.py
python
TradingCalendarDispatcher.__init__
(self, calendars, calendar_factories, aliases)
[]
def __init__(self, calendars, calendar_factories, aliases): self._calendars = calendars self._calendar_factories = dict(calendar_factories) self._aliases = dict(aliases)
[ "def", "__init__", "(", "self", ",", "calendars", ",", "calendar_factories", ",", "aliases", ")", ":", "self", ".", "_calendars", "=", "calendars", "self", ".", "_calendar_factories", "=", "dict", "(", "calendar_factories", ")", "self", ".", "_aliases", "=", ...
https://github.com/quantopian/trading_calendars/blob/19c4b677f13147928d34be5a3da50ba4161be45d/trading_calendars/calendar_utils.py#L165-L168
google/ctfscoreboard
28a8f6c30e401e07031741d5bafea3003e2d100e
scoreboard/models.py
python
Challenge.get_joined_query
(cls)
return cls.query.options( orm.joinedload(cls.answers).joinedload(Answer.team))
Get a prejoined-query with answers and teams.
Get a prejoined-query with answers and teams.
[ "Get", "a", "prejoined", "-", "query", "with", "answers", "and", "teams", "." ]
def get_joined_query(cls): """Get a prejoined-query with answers and teams.""" return cls.query.options( orm.joinedload(cls.answers).joinedload(Answer.team))
[ "def", "get_joined_query", "(", "cls", ")", ":", "return", "cls", ".", "query", ".", "options", "(", "orm", ".", "joinedload", "(", "cls", ".", "answers", ")", ".", "joinedload", "(", "Answer", ".", "team", ")", ")" ]
https://github.com/google/ctfscoreboard/blob/28a8f6c30e401e07031741d5bafea3003e2d100e/scoreboard/models.py#L573-L576
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
dragonfly/exd/worker_manager.py
python
MultiProcessingWorkerManager._rwm_set_up
(self)
Sets things up for the child.
Sets things up for the child.
[ "Sets", "things", "up", "for", "the", "child", "." ]
def _rwm_set_up(self): """ Sets things up for the child. """ # Create the result directories. """ self.result_dir_names = {wid:'%s/result_%s'%(self.tmp_dir, str(wid)) for wid in self.worker_ids} # Create the working directories self.working_dir_names = {wid:'%s/working_%s/tmp'%(self.tmp_dir, str(wid)) for wid in self.worker_ids} # Create the last receive times self.last_receive_times = {wid:0.0 for wid in self.worker_ids} # Create file names self._result_file_name = 'result.p' self._num_file_read_attempts = 10
[ "def", "_rwm_set_up", "(", "self", ")", ":", "# Create the result directories. \"\"\"", "self", ".", "result_dir_names", "=", "{", "wid", ":", "'%s/result_%s'", "%", "(", "self", ".", "tmp_dir", ",", "str", "(", "wid", ")", ")", "for", "wid", "in", "self", ...
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/dragonfly/exd/worker_manager.py#L227-L239
hakril/PythonForWindows
61e027a678d5b87aa64fcf8a37a6661a86236589
windows/com.py
python
Variant.guess_type_and_set_value
(self, value)
[]
def guess_type_and_set_value(self, value): for t, attr, check in self.CHECK_TYPE: try: checkres = check(value) except TypeError as e: continue if checkres: self.vt = t if attr is not None: setattr(self, attr, value) return True raise ValueError("Could not guess VT_TYPE for <{0}> of type <{1}>".format(value, type(value)))
[ "def", "guess_type_and_set_value", "(", "self", ",", "value", ")", ":", "for", "t", ",", "attr", ",", "check", "in", "self", ".", "CHECK_TYPE", ":", "try", ":", "checkres", "=", "check", "(", "value", ")", "except", "TypeError", "as", "e", ":", "contin...
https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/windows/com.py#L240-L251
HaoZhang95/Python24
b897224b8a0e6a5734f408df8c24846a98c553bf
00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/distlib/_backport/tarfile.py
python
ExFileObject.close
(self)
Close the file object.
Close the file object.
[ "Close", "the", "file", "object", "." ]
def close(self): """Close the file object. """ self.closed = True
[ "def", "close", "(", "self", ")", ":", "self", ".", "closed", "=", "True" ]
https://github.com/HaoZhang95/Python24/blob/b897224b8a0e6a5734f408df8c24846a98c553bf/00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/distlib/_backport/tarfile.py#L905-L908
llSourcell/AI_For_Music_Composition
795f8879158b238e7dc78d07e4451dcf54a2126c
musegan/model.py
python
Model.save_statistics
(self, filepath=None)
Save model statistics to file. Default to save to the log directory given as a global variable.
Save model statistics to file. Default to save to the log directory given as a global variable.
[ "Save", "model", "statistics", "to", "file", ".", "Default", "to", "save", "to", "the", "log", "directory", "given", "as", "a", "global", "variable", "." ]
def save_statistics(self, filepath=None): """Save model statistics to file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['log_dir'], 'model_statistics.txt') with open(filepath, 'w') as f: f.write(self.get_statistics())
[ "def", "save_statistics", "(", "self", ",", "filepath", "=", "None", ")", ":", "if", "filepath", "is", "None", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "config", "[", "'log_dir'", "]", ",", "'model_statistics.txt'", ")", ...
https://github.com/llSourcell/AI_For_Music_Composition/blob/795f8879158b238e7dc78d07e4451dcf54a2126c/musegan/model.py#L112-L119
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/admin/server.py
python
AdminServer.liveliness_handler
(self, request: web.BaseRequest)
Request handler for liveliness check. Args: request: aiohttp request object Returns: The web response, always indicating True
Request handler for liveliness check.
[ "Request", "handler", "for", "liveliness", "check", "." ]
async def liveliness_handler(self, request: web.BaseRequest): """ Request handler for liveliness check. Args: request: aiohttp request object Returns: The web response, always indicating True """ app_live = self.app._state["alive"] if app_live: return web.json_response({"alive": app_live}) else: raise web.HTTPServiceUnavailable(reason="Service not available")
[ "async", "def", "liveliness_handler", "(", "self", ",", "request", ":", "web", ".", "BaseRequest", ")", ":", "app_live", "=", "self", ".", "app", ".", "_state", "[", "\"alive\"", "]", "if", "app_live", ":", "return", "web", ".", "json_response", "(", "{"...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/admin/server.py#L663-L678
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
PyTorch/LanguageModeling/Transformer-XL/pytorch/utils/distributed.py
python
get_world_size
()
return world_size
Gets total number of distributed workers or returns one if distributed is not initialized.
Gets total number of distributed workers or returns one if distributed is not initialized.
[ "Gets", "total", "number", "of", "distributed", "workers", "or", "returns", "one", "if", "distributed", "is", "not", "initialized", "." ]
def get_world_size(): """ Gets total number of distributed workers or returns one if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size() else: world_size = 1 return world_size
[ "def", "get_world_size", "(", ")", ":", "if", "torch", ".", "distributed", ".", "is_available", "(", ")", "and", "torch", ".", "distributed", ".", "is_initialized", "(", ")", ":", "world_size", "=", "torch", ".", "distributed", ".", "get_world_size", "(", ...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/PyTorch/LanguageModeling/Transformer-XL/pytorch/utils/distributed.py#L57-L66
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/gtk_extras/treeview_extras.py
python
get_row
(mod, iter)
return row
Grab all values in iter and return as a list suitable for feeding to 'row' argument of append/prepend/insert
Grab all values in iter and return as a list suitable for feeding to 'row' argument of append/prepend/insert
[ "Grab", "all", "values", "in", "iter", "and", "return", "as", "a", "list", "suitable", "for", "feeding", "to", "row", "argument", "of", "append", "/", "prepend", "/", "insert" ]
def get_row (mod, iter): """Grab all values in iter and return as a list suitable for feeding to 'row' argument of append/prepend/insert""" n = 0 flag = True row = [] while flag: try: row.append(mod.get_value(iter,n)) except: flag=False n += 1 return row
[ "def", "get_row", "(", "mod", ",", "iter", ")", ":", "n", "=", "0", "flag", "=", "True", "row", "=", "[", "]", "while", "flag", ":", "try", ":", "row", ".", "append", "(", "mod", ".", "get_value", "(", "iter", ",", "n", ")", ")", "except", ":...
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/gtk_extras/treeview_extras.py#L156-L168
mihaip/mail-trends
312b5be7f8f0a5933b05c75e229eda8e44c3c920
main.py
python
GetOptsMap
()
return opts_map
[]
def GetOptsMap(): opts, args = getopt.getopt(sys.argv[1:], "", [ # Standard options "username=", "password=", "use_ssl", "server=", # Other params "filter_out=", "me=", # Development options "record", "replay", "max_messages=", "random_subset", "skip_labels"]) opts_map = {} for name, value in opts: opts_map[name[2:]] = value assert "username" in opts_map if "password" not in opts_map: opts_map["password"] = getpass.getpass( prompt="Password for %s: " % opts_map["username"]) assert "password" in opts_map assert "server" in opts_map return opts_map
[ "def", "GetOptsMap", "(", ")", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "\"\"", ",", "[", "# Standard options", "\"username=\"", ",", "\"password=\"", ",", "\"use_ssl\"", ",", "\"server=\""...
https://github.com/mihaip/mail-trends/blob/312b5be7f8f0a5933b05c75e229eda8e44c3c920/main.py#L18-L44
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/insults/insults.py
python
ITerminalTransport.nextLine
()
Move the cursor to the first position on the next line, performing scrolling if necessary.
Move the cursor to the first position on the next line, performing scrolling if necessary.
[ "Move", "the", "cursor", "to", "the", "first", "position", "on", "the", "next", "line", "performing", "scrolling", "if", "necessary", "." ]
def nextLine(): """ Move the cursor to the first position on the next line, performing scrolling if necessary. """
[ "def", "nextLine", "(", ")", ":" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/insults/insults.py#L140-L143
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/package_help.py
python
PackageHelp.open
(self, section_index=0)
Launch a help section.
Launch a help section.
[ "Launch", "a", "help", "section", "." ]
def open(self, section_index=0): """Launch a help section.""" uri = self._sections[section_index][1] if len(uri.split()) == 1: self._open_url(uri) else: if self._verbose: print("running command: %s" % uri) with Popen(uri, shell=True) as p: p.wait()
[ "def", "open", "(", "self", ",", "section_index", "=", "0", ")", ":", "uri", "=", "self", ".", "_sections", "[", "section_index", "]", "[", "1", "]", "if", "len", "(", "uri", ".", "split", "(", ")", ")", "==", "1", ":", "self", ".", "_open_url", ...
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/package_help.py#L107-L117
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/parser/template/nodes/authorise.py
python
TemplateAuthoriseNode.__init__
(self)
[]
def __init__(self): TemplateNode.__init__(self) self._role = None self._denied_srai = None
[ "def", "__init__", "(", "self", ")", ":", "TemplateNode", ".", "__init__", "(", "self", ")", "self", ".", "_role", "=", "None", "self", ".", "_denied_srai", "=", "None" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/parser/template/nodes/authorise.py#L24-L27
khalim19/gimp-plugin-export-layers
b37255f2957ad322f4d332689052351cdea6e563
export_layers/pygimplib/setting/presenters_gtk.py
python
GimpUiPatternSelectButtonPresenter._create_gui_element
(self, setting)
return gimpui.PatternSelectButton(setting.display_name, setting.value)
[]
def _create_gui_element(self, setting): return gimpui.PatternSelectButton(setting.display_name, setting.value)
[ "def", "_create_gui_element", "(", "self", ",", "setting", ")", ":", "return", "gimpui", ".", "PatternSelectButton", "(", "setting", ".", "display_name", ",", "setting", ".", "value", ")" ]
https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/setting/presenters_gtk.py#L614-L615
movidius/ncappzoo
5d06afdbfce51b0627fab05d1941a30ecffee172
apps/driving_pi/car_pi.py
python
DriveBrickPi3.speed
(self)
return self.__speed
Get speed value of the car :return: speed value
Get speed value of the car :return: speed value
[ "Get", "speed", "value", "of", "the", "car", ":", "return", ":", "speed", "value" ]
def speed(self): """ Get speed value of the car :return: speed value """ return self.__speed
[ "def", "speed", "(", "self", ")", ":", "return", "self", ".", "__speed" ]
https://github.com/movidius/ncappzoo/blob/5d06afdbfce51b0627fab05d1941a30ecffee172/apps/driving_pi/car_pi.py#L42-L47
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/ownomogram.py
python
RulerItem.__init__
(self, name, values, scale, name_offset, offset, labels=None)
[]
def __init__(self, name, values, scale, name_offset, offset, labels=None): super().__init__() # leading label font = name.document().defaultFont() if self.bold_label: font.setWeight(QFont.Bold) name.setFont(font) name.setPos(name_offset, -10) name.setParentItem(self) # prediction marker self.dot = self.DOT_ITEM_CLS(self.DOT_RADIUS, scale, offset, values[0], values[-1]) self.dot.setParentItem(self) # pylint: disable=unused-variable # line line = QGraphicsLineItem(min(values) * scale + offset, 0, max(values) * scale + offset, 0, self) if labels is None: labels = [str(abs(v) if v == -0 else v) for v in values] old_x_tick = None shown_items = [] w = QGraphicsSimpleTextItem(labels[0]).boundingRect().width() text_finish = values[0] * scale - w + offset - 10 for i, (label, value) in enumerate(zip(labels, values)): text = QGraphicsSimpleTextItem(label) x_text = value * scale - text.boundingRect().width() / 2 + offset if text_finish > x_text - 10: y_text, y_tick = self.DOT_RADIUS * 0.7, 0 text_finish = values[0] * scale + offset else: y_text = - text.boundingRect().height() - self.DOT_RADIUS * 0.7 y_tick = - self.tick_height text_finish = x_text + text.boundingRect().width() text.setPos(x_text, y_text) if not collides(text, shown_items): text.setParentItem(self) shown_items.append(text) x_tick = value * scale - self.tick_width / 2 + offset tick = QGraphicsRectItem( x_tick, y_tick, self.tick_width, self.tick_height, self) tick.setBrush(QColor(Qt.black)) if self.half_tick_height and i: x = x_tick - (x_tick - old_x_tick) / 2 half_tick = QGraphicsLineItem(x, - self.half_tick_height, x, 0, self) old_x_tick = x_tick
[ "def", "__init__", "(", "self", ",", "name", ",", "values", ",", "scale", ",", "name_offset", ",", "offset", ",", "labels", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "# leading label", "font", "=", "name", ".", "document", ...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/ownomogram.py#L376-L430
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/socketserver.py
python
TCPServer.get_request
(self)
return self.socket.accept()
Get the request and client address from the socket. May be overridden.
Get the request and client address from the socket.
[ "Get", "the", "request", "and", "client", "address", "from", "the", "socket", "." ]
def get_request(self): """Get the request and client address from the socket. May be overridden. """ return self.socket.accept()
[ "def", "get_request", "(", "self", ")", ":", "return", "self", ".", "socket", ".", "accept", "(", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/socketserver.py#L471-L477
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/http/multipartparser.py
python
ChunkIter.__iter__
(self)
return self
[]
def __iter__(self): return self
[ "def", "__iter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/http/multipartparser.py#L457-L458
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/GrepDialog.py
python
grep
(text, io=None, flist=None)
[]
def grep(text, io=None, flist=None): root = text._root() engine = SearchEngine.get(root) if not hasattr(engine, "_grepdialog"): engine._grepdialog = GrepDialog(root, engine, flist) dialog = engine._grepdialog searchphrase = text.get("sel.first", "sel.last") dialog.open(text, searchphrase, io)
[ "def", "grep", "(", "text", ",", "io", "=", "None", ",", "flist", "=", "None", ")", ":", "root", "=", "text", ".", "_root", "(", ")", "engine", "=", "SearchEngine", ".", "get", "(", "root", ")", "if", "not", "hasattr", "(", "engine", ",", "\"_gre...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/GrepDialog.py#L13-L20
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/httputil.py
python
Response._response
(self, message="", **argv)
[]
def _response(self, message="", **argv): if self.template: message = self.template % message elif self.mako_lookup and self.mako_template: argv["message"] = message mte = self.mako_lookup.get_template(self.mako_template) message = mte.render(**argv) if isinstance(message, six.string_types): return [message.encode('utf-8')] elif isinstance(message, six.binary_type): return [message] else: return message
[ "def", "_response", "(", "self", ",", "message", "=", "\"\"", ",", "*", "*", "argv", ")", ":", "if", "self", ".", "template", ":", "message", "=", "self", ".", "template", "%", "message", "elif", "self", ".", "mako_lookup", "and", "self", ".", "mako_...
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/httputil.py#L56-L69
iduta/iresnet
babdc4f5946f64905710cd64a5bd6c164a805c9e
models/resgroupfix.py
python
conv1x1
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
1x1 convolution
1x1 convolution
[ "1x1", "convolution" ]
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
[ "def", "conv1x1", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "1", ",", "stride", "=", "stride", ",", "bias", "=", "False", ")" ]
https://github.com/iduta/iresnet/blob/babdc4f5946f64905710cd64a5bd6c164a805c9e/models/resgroupfix.py#L32-L34
vibora-io/vibora
4cda888f89aec6bfb2541ee53548ae1bf50fbf1b
vibora/client/response.py
python
Response.receive_headers
(self)
:return:
[]
async def receive_headers(self): """ :return: """ if self._parser_status != ResponseStatus.PENDING_HEADERS: return try: self._parser.feed(await self._connection.read_until(b'\r\n\r\n')) if self._headers.get('content-encoding') == 'gzip': self._decoder = GzipDecoder() self._parser_status = ResponseStatus.PENDING_BODY except OSError as error: # In case any network error occurs we should discard this connection. self._parser_status = ResponseStatus.ERROR self._connection.close() raise error
[ "async", "def", "receive_headers", "(", "self", ")", ":", "if", "self", ".", "_parser_status", "!=", "ResponseStatus", ".", "PENDING_HEADERS", ":", "return", "try", ":", "self", ".", "_parser", ".", "feed", "(", "await", "self", ".", "_connection", ".", "r...
https://github.com/vibora-io/vibora/blob/4cda888f89aec6bfb2541ee53548ae1bf50fbf1b/vibora/client/response.py#L139-L155
carla-simulator/scenario_runner
f4d00d88eda4212a1e119515c96281a4be5c234e
srunner/scenarios/background_activity.py
python
BackgroundBehavior.__init__
(self, ego_actor, route, night_mode=False, debug=False, name="BackgroundBehavior")
Setup class members
Setup class members
[ "Setup", "class", "members" ]
def __init__(self, ego_actor, route, night_mode=False, debug=False, name="BackgroundBehavior"): """ Setup class members """ super(BackgroundBehavior, self).__init__(name) self.debug = debug self._map = CarlaDataProvider.get_map() self._world = CarlaDataProvider.get_world() timestep = self._world.get_snapshot().timestamp.delta_seconds self._tm = CarlaDataProvider.get_client().get_trafficmanager( CarlaDataProvider.get_traffic_manager_port()) self._tm.global_percentage_speed_difference(0.0) self._night_mode = night_mode # Global variables self._ego_actor = ego_actor self._ego_state = 'road' self._route_index = 0 self._get_route_data(route) self._spawn_vertical_shift = 0.2 self._reuse_dist = 10 # When spawning actors, might reuse actors closer to this distance self._spawn_free_radius = 20 # Sources closer to the ego will not spawn actors self._fake_junction_ids = [] self._fake_lane_pair_keys = [] # Road variables self._road_actors = [] self._road_back_actors = {} # Dictionary mapping the actors behind the ego to their lane self._road_ego_key = None self._road_extra_front_actors = 0 self._road_sources = [] self._road_checker_index = 0 self._road_ego_key = "" self._road_front_vehicles = 3 # Amount of vehicles in front of the ego self._road_back_vehicles = 3 # Amount of vehicles behind the ego self._road_vehicle_dist = 8 # Distance road vehicles leave betweeen each other[m] self._road_spawn_dist = 11 # Initial distance between spawned road vehicles [m] self._road_new_sources_dist = 20 # Distance of the source to the start of the new lanes self._radius_increase_ratio = 1.8 # Meters the radius increases per m/s of the ego self._extra_radius = 0.0 # Extra distance to avoid the road behavior from blocking self._extra_radius_increase_ratio = 0.5 * timestep # Distance the radius increases per tick (0.5 m/s) self._max_extra_radius = 10 # Max extra distance self._base_min_radius = 0 self._base_max_radius = 0 self._min_radius = 0 self._max_radius = 0 self._junction_detection_dist = 0 self._get_road_radius() # Junction variables self._junctions = [] self._active_junctions = [] self._junction_sources_dist = 40 # Distance from the entry sources to the junction [m] self._junction_vehicle_dist = 8 # Distance junction vehicles leave betweeen each other[m] self._junction_spawn_dist = 10 # Initial distance between spawned junction vehicles [m] self._junction_sources_max_actors = 5 # Maximum vehicles alive at the same time per source # Opposite lane variables self._opposite_actors = [] self._opposite_sources = [] self._opposite_route_index = 0 self._opposite_removal_dist = 30 # Distance at which actors are destroyed self._opposite_sources_dist = 60 # Distance from the ego to the opposite sources [m] self._opposite_vehicle_dist = 10 # Distance opposite vehicles leave betweeen each other[m] self._opposite_spawn_dist = 20 # Initial distance between spawned opposite vehicles [m] self._opposite_sources_max_actors = 8 # Maximum vehicles alive at the same time per source # Scenario 2 variables self._is_scenario_2_active = False self._scenario_2_actors = [] self._activate_break_scenario = False self._break_duration = 7 # Duration of the scenario self._next_scenario_time = float('inf') # Scenario 4 variables self._is_scenario_4_active = False self._scenario_4_actors = [] self._ego_exitted_junction = False self._crossing_dist = None # Distance between the crossing object and the junction exit self._start_ego_wp = None # Junction scenario variables self.scenario_info = { 'direction': None, 'remove_entries': False, 'remove_middle': False, 'remove_exits': False, }
[ "def", "__init__", "(", "self", ",", "ego_actor", ",", "route", ",", "night_mode", "=", "False", ",", "debug", "=", "False", ",", "name", "=", "\"BackgroundBehavior\"", ")", ":", "super", "(", "BackgroundBehavior", ",", "self", ")", ".", "__init__", "(", ...
https://github.com/carla-simulator/scenario_runner/blob/f4d00d88eda4212a1e119515c96281a4be5c234e/srunner/scenarios/background_activity.py#L243-L335
analysiscenter/batchflow
294747da0bca309785f925be891441fdd824e9fa
batchflow/models/torch/base.py
python
TorchModel.combine_configs
(self)
return config
Combine default configuration and the external one.
Combine default configuration and the external one.
[ "Combine", "default", "configuration", "and", "the", "external", "one", "." ]
def combine_configs(self): """ Combine default configuration and the external one. """ config = self.default_config() + self.external_config return config
[ "def", "combine_configs", "(", "self", ")", ":", "config", "=", "self", ".", "default_config", "(", ")", "+", "self", ".", "external_config", "return", "config" ]
https://github.com/analysiscenter/batchflow/blob/294747da0bca309785f925be891441fdd824e9fa/batchflow/models/torch/base.py#L501-L504
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/layout/mapbox/layer/_line.py
python
Line.dashsrc
(self)
return self["dashsrc"]
Sets the source reference on Chart Studio Cloud for `dash`. The 'dashsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for `dash`. The 'dashsrc' property must be specified as a string or as a plotly.grid_objs.Column object
[ "Sets", "the", "source", "reference", "on", "Chart", "Studio", "Cloud", "for", "dash", ".", "The", "dashsrc", "property", "must", "be", "specified", "as", "a", "string", "or", "as", "a", "plotly", ".", "grid_objs", ".", "Column", "object" ]
def dashsrc(self): """ Sets the source reference on Chart Studio Cloud for `dash`. The 'dashsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["dashsrc"]
[ "def", "dashsrc", "(", "self", ")", ":", "return", "self", "[", "\"dashsrc\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/layout/mapbox/layer/_line.py#L37-L48
sergiocorreia/panflute
b9546cf7b88fdc9f00117fca395c4d3590f45769
panflute/base.py
python
Element._set_ica
(self, identifier, classes, attributes)
[]
def _set_ica(self, identifier, classes, attributes): self.identifier = check_type(identifier, str) self.classes = [check_type(cl, str) for cl in classes] self.attributes = dict(attributes)
[ "def", "_set_ica", "(", "self", ",", "identifier", ",", "classes", ",", "attributes", ")", ":", "self", ".", "identifier", "=", "check_type", "(", "identifier", ",", "str", ")", "self", ".", "classes", "=", "[", "check_type", "(", "cl", ",", "str", ")"...
https://github.com/sergiocorreia/panflute/blob/b9546cf7b88fdc9f00117fca395c4d3590f45769/panflute/base.py#L82-L85
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/cherrypy/lib/cptools.py
python
SessionAuth.do_check
(self)
Assert username. May raise redirect, or return True if request handled.
Assert username. May raise redirect, or return True if request handled.
[ "Assert", "username", ".", "May", "raise", "redirect", "or", "return", "True", "if", "request", "handled", "." ]
def do_check(self): """Assert username. May raise redirect, or return True if request handled.""" sess = cherrypy.session request = cherrypy.serving.request response = cherrypy.serving.response username = sess.get(self.session_key) if not username: sess[self.session_key] = username = self.anonymous() if self.debug: cherrypy.log('No session[username], trying anonymous', 'TOOLS.SESSAUTH') if not username: url = cherrypy.url(qs=request.query_string) if self.debug: cherrypy.log('No username, routing to login_screen with ' 'from_page %r' % url, 'TOOLS.SESSAUTH') response.body = self.login_screen(url) if "Content-Length" in response.headers: # Delete Content-Length header so finalize() recalcs it. del response.headers["Content-Length"] return True if self.debug: cherrypy.log('Setting request.login to %r' % username, 'TOOLS.SESSAUTH') request.login = username self.on_check(username)
[ "def", "do_check", "(", "self", ")", ":", "sess", "=", "cherrypy", ".", "session", "request", "=", "cherrypy", ".", "serving", ".", "request", "response", "=", "cherrypy", ".", "serving", ".", "response", "username", "=", "sess", ".", "get", "(", "self",...
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/cherrypy/lib/cptools.py#L340-L364
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_obj.py
python
OCObject.run_ansible
(params, check_mode=False)
run the oc_obj module
run the oc_obj module
[ "run", "the", "oc_obj", "module" ]
def run_ansible(params, check_mode=False): '''run the oc_obj module''' ocobj = OCObject(params['kind'], params['namespace'], params['name'], params['selector'], kubeconfig=params['kubeconfig'], verbose=params['debug'], all_namespaces=params['all_namespaces'], field_selector=params['field_selector']) state = params['state'] api_rval = ocobj.get() ##### # Get ##### if state == 'list': if api_rval['returncode'] != 0: return {'changed': False, 'failed': True, 'msg': api_rval} return {'changed': False, 'results': api_rval, 'state': state} ######## # Delete ######## if state == 'absent': # verify it's not in our results # pylint: disable=too-many-boolean-expressions if (params['name'] is not None or params['selector'] is not None) and \ (len(api_rval['results']) == 0 or \ (not api_rval['results'][0]) or \ ('items' in api_rval['results'][0] and len(api_rval['results'][0]['items']) == 0)): return {'changed': False, 'state': state} if check_mode: return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete'} api_rval = ocobj.delete() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': state} # create/update: Must define a name beyond this point if not params['name']: return {'failed': True, 'msg': 'Please specify a name when state is present.'} if state == 'present': ######## # Create ######## if not Utils.exists(api_rval['results'], params['name']): if check_mode: return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create'} # Create it here api_rval = ocobj.create(params['files'], params['content']) if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} # return the created object api_rval = ocobj.get() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} # Remove files if params['files'] and params['delete_after']: Utils.cleanup(params['files']) return {'changed': True, 'results': api_rval, 'state': state} ######## # Update ######## # if a file path is passed, use it. update = ocobj.needs_update(params['files'], params['content']) if not isinstance(update, bool): return {'failed': True, 'msg': update} # No changes if not update: if params['files'] and params['delete_after']: Utils.cleanup(params['files']) return {'changed': False, 'results': api_rval['results'][0], 'state': state} if check_mode: return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'} api_rval = ocobj.update(params['files'], params['content'], params['force']) if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} # return the created object api_rval = ocobj.get() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': state}
[ "def", "run_ansible", "(", "params", ",", "check_mode", "=", "False", ")", ":", "ocobj", "=", "OCObject", "(", "params", "[", "'kind'", "]", ",", "params", "[", "'namespace'", "]", ",", "params", "[", "'name'", "]", ",", "params", "[", "'selector'", "]...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_obj.py#L1599-L1707
magic-wormhole/magic-wormhole
e522a3992217b433ac2c36543bf85c27a7226ed9
src/wormhole/observer.py
python
SequenceObserver.fire
(self, result)
[]
def fire(self, result): if isinstance(result, Failure): self._error = result for d in self._observers: self._eq.eventually(d.errback, self._error) self._observers = [] else: self._results.append(result) if self._observers: d = self._observers.pop(0) self._eq.eventually(d.callback, self._results.pop(0))
[ "def", "fire", "(", "self", ",", "result", ")", ":", "if", "isinstance", "(", "result", ",", "Failure", ")", ":", "self", ".", "_error", "=", "result", "for", "d", "in", "self", ".", "_observers", ":", "self", ".", "_eq", ".", "eventually", "(", "d...
https://github.com/magic-wormhole/magic-wormhole/blob/e522a3992217b433ac2c36543bf85c27a7226ed9/src/wormhole/observer.py#L62-L72
duckduckgo/zeroclickinfo-fathead
477c5652f6576746618dbb8158b67f0960ae9f56
lib/fathead/python/redirect.py
python
Entry.parse
(self, input_obj)
return self.data
Try to parse given input into a valid entry. Args: input_obj: TSV string or list of data. Returns: List of data Raises: Throws BadEntryException if data is invalid.
Try to parse given input into a valid entry. Args: input_obj: TSV string or list of data.
[ "Try", "to", "parse", "given", "input", "into", "a", "valid", "entry", ".", "Args", ":", "input_obj", ":", "TSV", "string", "or", "list", "of", "data", "." ]
def parse(self, input_obj): """ Try to parse given input into a valid entry. Args: input_obj: TSV string or list of data. Returns: List of data Raises: Throws BadEntryException if data is invalid. """ if isinstance(input_obj, str): processed = input_obj.split('\t') self.data = processed elif isinstance(input_obj, list): self.data = input_obj try: self.key = self.data[0].strip() self.entry_type = self.data[1].strip() self.reference = self.data[2].strip() if len(self.data) > 3: self.category = self.data[4].strip() self.related = self.data[6].strip() self.abstract = self.data[11].strip() self.anchor = self.data[12].strip() elif self.entry_type == 13 and len(self.data) != 13: raise BadEntryException except Exception as e: raise BadEntryException('Article had invalid number of elements.') if self.entry_type == 'A': self.parse_alternative_keys() return self.data
[ "def", "parse", "(", "self", ",", "input_obj", ")", ":", "if", "isinstance", "(", "input_obj", ",", "str", ")", ":", "processed", "=", "input_obj", ".", "split", "(", "'\\t'", ")", "self", ".", "data", "=", "processed", "elif", "isinstance", "(", "inpu...
https://github.com/duckduckgo/zeroclickinfo-fathead/blob/477c5652f6576746618dbb8158b67f0960ae9f56/lib/fathead/python/redirect.py#L54-L87
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/simulators/bullet.py
python
Bullet.compute_view_matrix_from_ypr
(self, target_position, distance, yaw, pitch, roll, up_axis_index=2)
return np.asarray(view).reshape(4, 4).T
Compute the view matrix from the yaw, pitch, and roll angles. The view matrix is the 4x4 matrix that maps the world coordinates into the camera coordinates. Basically, it applies a rotation and translation such that the world is in front of the camera. That is, instead of turning the camera to capture what we want in the world, we keep the camera fixed and turn the world. Args: target_position (np.array[float[3]]): target focus point in Cartesian world coordinates distance (float): distance from eye to focus point yaw (float): yaw angle in radians left/right around up-axis pitch (float): pitch in radians up/down. roll (float): roll in radians around forward vector up_axis_index (int): either 1 for Y or 2 for Z axis up. Returns: np.array[float[4,4]]: the view matrix More info: [1] http://www.codinglabs.net/article_world_view_projection_matrix.aspx [2] http://www.thecodecrate.com/opengl-es/opengl-transformation-matrices/
Compute the view matrix from the yaw, pitch, and roll angles.
[ "Compute", "the", "view", "matrix", "from", "the", "yaw", "pitch", "and", "roll", "angles", "." ]
def compute_view_matrix_from_ypr(self, target_position, distance, yaw, pitch, roll, up_axis_index=2): """Compute the view matrix from the yaw, pitch, and roll angles. The view matrix is the 4x4 matrix that maps the world coordinates into the camera coordinates. Basically, it applies a rotation and translation such that the world is in front of the camera. That is, instead of turning the camera to capture what we want in the world, we keep the camera fixed and turn the world. Args: target_position (np.array[float[3]]): target focus point in Cartesian world coordinates distance (float): distance from eye to focus point yaw (float): yaw angle in radians left/right around up-axis pitch (float): pitch in radians up/down. roll (float): roll in radians around forward vector up_axis_index (int): either 1 for Y or 2 for Z axis up. Returns: np.array[float[4,4]]: the view matrix More info: [1] http://www.codinglabs.net/article_world_view_projection_matrix.aspx [2] http://www.thecodecrate.com/opengl-es/opengl-transformation-matrices/ """ view = self.sim.computeViewMatrixFromYawPitchRoll(cameraTargetPosition=target_position, distance=distance, yaw=np.rad2deg(yaw), pitch=np.rad2deg(pitch), roll=np.rad2deg(roll), upAxisIndex=up_axis_index) return np.asarray(view).reshape(4, 4).T
[ "def", "compute_view_matrix_from_ypr", "(", "self", ",", "target_position", ",", "distance", ",", "yaw", ",", "pitch", ",", "roll", ",", "up_axis_index", "=", "2", ")", ":", "view", "=", "self", ".", "sim", ".", "computeViewMatrixFromYawPitchRoll", "(", "camer...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/simulators/bullet.py#L2613-L2638
lvpengyuan/masktextspotter.caffe2
da99ef31f5ccb4de5248bb881d5b4a291910c8ae
lib/utils/segms.py
python
rle_mask_voting
( top_masks, all_masks, all_dets, iou_thresh, binarize_thresh, method='AVG' )
return top_segms_out
Returns new masks (in correspondence with `top_masks`) by combining multiple overlapping masks coming from the pool of `all_masks`. Two methods for combining masks are supported: 'AVG' uses a weighted average of overlapping mask pixels; 'UNION' takes the union of all mask pixels.
Returns new masks (in correspondence with `top_masks`) by combining multiple overlapping masks coming from the pool of `all_masks`. Two methods for combining masks are supported: 'AVG' uses a weighted average of overlapping mask pixels; 'UNION' takes the union of all mask pixels.
[ "Returns", "new", "masks", "(", "in", "correspondence", "with", "top_masks", ")", "by", "combining", "multiple", "overlapping", "masks", "coming", "from", "the", "pool", "of", "all_masks", ".", "Two", "methods", "for", "combining", "masks", "are", "supported", ...
def rle_mask_voting( top_masks, all_masks, all_dets, iou_thresh, binarize_thresh, method='AVG' ): """Returns new masks (in correspondence with `top_masks`) by combining multiple overlapping masks coming from the pool of `all_masks`. Two methods for combining masks are supported: 'AVG' uses a weighted average of overlapping mask pixels; 'UNION' takes the union of all mask pixels. """ if len(top_masks) == 0: return all_not_crowd = [False] * len(all_masks) top_to_all_overlaps = mask_util.iou(top_masks, all_masks, all_not_crowd) decoded_all_masks = [ np.array(mask_util.decode(rle), dtype=np.float32) for rle in all_masks ] decoded_top_masks = [ np.array(mask_util.decode(rle), dtype=np.float32) for rle in top_masks ] all_boxes = all_dets[:, :4].astype(np.int32) all_scores = all_dets[:, 4] # Fill box support with weights mask_shape = decoded_all_masks[0].shape mask_weights = np.zeros((len(all_masks), mask_shape[0], mask_shape[1])) for k in range(len(all_masks)): ref_box = all_boxes[k] x_0 = max(ref_box[0], 0) x_1 = min(ref_box[2] + 1, mask_shape[1]) y_0 = max(ref_box[1], 0) y_1 = min(ref_box[3] + 1, mask_shape[0]) mask_weights[k, y_0:y_1, x_0:x_1] = all_scores[k] mask_weights = np.maximum(mask_weights, 1e-5) top_segms_out = [] for k in range(len(top_masks)): # Corner case of empty mask if decoded_top_masks[k].sum() == 0: top_segms_out.append(top_masks[k]) continue inds_to_vote = np.where(top_to_all_overlaps[k] >= iou_thresh)[0] # Only matches itself if len(inds_to_vote) == 1: top_segms_out.append(top_masks[k]) continue masks_to_vote = [decoded_all_masks[i] for i in inds_to_vote] if method == 'AVG': ws = mask_weights[inds_to_vote] soft_mask = np.average(masks_to_vote, axis=0, weights=ws) mask = np.array(soft_mask > binarize_thresh, dtype=np.uint8) elif method == 'UNION': # Any pixel that's on joins the mask soft_mask = np.sum(masks_to_vote, axis=0) mask = np.array(soft_mask > 1e-5, dtype=np.uint8) else: raise NotImplementedError('Method {} is unknown'.format(method)) rle = mask_util.encode(np.array(mask[:, :, np.newaxis], order='F'))[0] top_segms_out.append(rle) return top_segms_out
[ "def", "rle_mask_voting", "(", "top_masks", ",", "all_masks", ",", "all_dets", ",", "iou_thresh", ",", "binarize_thresh", ",", "method", "=", "'AVG'", ")", ":", "if", "len", "(", "top_masks", ")", "==", "0", ":", "return", "all_not_crowd", "=", "[", "False...
https://github.com/lvpengyuan/masktextspotter.caffe2/blob/da99ef31f5ccb4de5248bb881d5b4a291910c8ae/lib/utils/segms.py#L241-L302
kevoreilly/CAPEv2
6cf79c33264624b3604d4cd432cde2a6b4536de6
modules/machinery/vsphere.py
python
vSphere._stop_virtual_machine
(self, vm)
Power off a virtual machine
Power off a virtual machine
[ "Power", "off", "a", "virtual", "machine" ]
def _stop_virtual_machine(self, vm): """Power off a virtual machine""" log.info("Powering off virtual machine %s", vm.summary.config.name) task = vm.PowerOffVM_Task() try: self._wait_task(task) except CuckooMachineError as e: log.error("PowerOffVM: %s", e)
[ "def", "_stop_virtual_machine", "(", "self", ",", "vm", ")", ":", "log", ".", "info", "(", "\"Powering off virtual machine %s\"", ",", "vm", ".", "summary", ".", "config", ".", "name", ")", "task", "=", "vm", ".", "PowerOffVM_Task", "(", ")", "try", ":", ...
https://github.com/kevoreilly/CAPEv2/blob/6cf79c33264624b3604d4cd432cde2a6b4536de6/modules/machinery/vsphere.py#L316-L323
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/httplib2/__init__.py
python
HTTPResponse__getheaders
(self)
return self.msg.items()
Return list of (header, value) tuples.
Return list of (header, value) tuples.
[ "Return", "list", "of", "(", "header", "value", ")", "tuples", "." ]
def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items()
[ "def", "HTTPResponse__getheaders", "(", "self", ")", ":", "if", "self", ".", "msg", "is", "None", ":", "raise", "httplib", ".", "ResponseNotReady", "(", ")", "return", "self", ".", "msg", ".", "items", "(", ")" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/httplib2/__init__.py#L104-L108
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/gree/climate.py
python
GreeClimateEntity.async_set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
[ "Set", "new", "target", "temperature", "." ]
async def async_set_temperature(self, **kwargs): """Set new target temperature.""" if ATTR_TEMPERATURE not in kwargs: raise ValueError(f"Missing parameter {ATTR_TEMPERATURE}") temperature = kwargs[ATTR_TEMPERATURE] _LOGGER.debug( "Setting temperature to %d for %s", temperature, self._name, ) self.coordinator.device.target_temperature = round(temperature) await self.coordinator.push_state_update() self.async_write_ha_state()
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "ATTR_TEMPERATURE", "not", "in", "kwargs", ":", "raise", "ValueError", "(", "f\"Missing parameter {ATTR_TEMPERATURE}\"", ")", "temperature", "=", "kwargs", "[", "ATTR_TE...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/gree/climate.py#L177-L191
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/operator/interp_operator.py
python
setitem
(space, w_obj, w_key, w_value)
setitem(a, b, c) -- Same as a[b] = c.
setitem(a, b, c) -- Same as a[b] = c.
[ "setitem", "(", "a", "b", "c", ")", "--", "Same", "as", "a", "[", "b", "]", "=", "c", "." ]
def setitem(space, w_obj, w_key, w_value): 'setitem(a, b, c) -- Same as a[b] = c.' space.setitem(w_obj, w_key, w_value)
[ "def", "setitem", "(", "space", ",", "w_obj", ",", "w_key", ",", "w_value", ")", ":", "space", ".", "setitem", "(", "w_obj", ",", "w_key", ",", "w_value", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/operator/interp_operator.py#L147-L149
danielfm/pybreaker
1dbcbda76dda1d1d3a9df25cbe1912655dbbf6cc
src/pybreaker.py
python
CircuitBreaker.call_async
(self, func, *args, **kwargs)
return wrapped()
Calls async `func` with the given `args` and `kwargs` according to the rules implemented by the current state of this circuit breaker. Return a closure to prevent import errors when using without tornado present
Calls async `func` with the given `args` and `kwargs` according to the rules implemented by the current state of this circuit breaker.
[ "Calls", "async", "func", "with", "the", "given", "args", "and", "kwargs", "according", "to", "the", "rules", "implemented", "by", "the", "current", "state", "of", "this", "circuit", "breaker", "." ]
def call_async(self, func, *args, **kwargs): """ Calls async `func` with the given `args` and `kwargs` according to the rules implemented by the current state of this circuit breaker. Return a closure to prevent import errors when using without tornado present """ @gen.coroutine def wrapped(): with self._lock: ret = yield self.state.call_async(func, *args, **kwargs) raise gen.Return(ret) return wrapped()
[ "def", "call_async", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "gen", ".", "coroutine", "def", "wrapped", "(", ")", ":", "with", "self", ".", "_lock", ":", "ret", "=", "yield", "self", ".", "state", ".", ...
https://github.com/danielfm/pybreaker/blob/1dbcbda76dda1d1d3a9df25cbe1912655dbbf6cc/src/pybreaker.py#L218-L230
styxit/HTPC-Manager
490697460b4fa1797106aece27d873bc256b2ff1
libs/cherrypy/lib/sessions.py
python
Session.save
(self)
Save session data.
Save session data.
[ "Save", "session", "data", "." ]
def save(self): """Save session data.""" try: # If session data has never been loaded then it's never been # accessed: no need to save it if self.loaded: t = datetime.timedelta(seconds = self.timeout * 60) expiration_time = self.now() + t if self.debug: cherrypy.log('Saving with expiry %s' % expiration_time, 'TOOLS.SESSIONS') self._save(expiration_time) finally: if self.locked: # Always release the lock if the user didn't release it self.release_lock()
[ "def", "save", "(", "self", ")", ":", "try", ":", "# If session data has never been loaded then it's never been", "# accessed: no need to save it", "if", "self", ".", "loaded", ":", "t", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "timeout...
https://github.com/styxit/HTPC-Manager/blob/490697460b4fa1797106aece27d873bc256b2ff1/libs/cherrypy/lib/sessions.py#L214-L230
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/utilities/errors.py
python
send_errors_to_logging
()
return obs.observe(error_output)
Send all VTK error/warning messages to Python's logging module.
Send all VTK error/warning messages to Python's logging module.
[ "Send", "all", "VTK", "error", "/", "warning", "messages", "to", "Python", "s", "logging", "module", "." ]
def send_errors_to_logging(): """Send all VTK error/warning messages to Python's logging module.""" error_output = _vtk.vtkStringOutputWindow() error_win = _vtk.vtkOutputWindow() error_win.SetInstance(error_output) obs = Observer() return obs.observe(error_output)
[ "def", "send_errors_to_logging", "(", ")", ":", "error_output", "=", "_vtk", ".", "vtkStringOutputWindow", "(", ")", "error_win", "=", "_vtk", ".", "vtkOutputWindow", "(", ")", "error_win", ".", "SetInstance", "(", "error_output", ")", "obs", "=", "Observer", ...
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/utilities/errors.py#L171-L177
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/mako/_ast_util.py
python
SourceGenerator.__init__
(self, indent_with)
[]
def __init__(self, indent_with): self.result = [] self.indent_with = indent_with self.indentation = 0 self.new_lines = 0
[ "def", "__init__", "(", "self", ",", "indent_with", ")", ":", "self", ".", "result", "=", "[", "]", "self", ".", "indent_with", "=", "indent_with", "self", ".", "indentation", "=", "0", "self", ".", "new_lines", "=", "0" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/mako/_ast_util.py#L361-L365
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_modflow_modelinstance/models.py
python
MODFLOWModelInstanceMetaData.stress_period
(self)
return self._stress_period.all().first()
[]
def stress_period(self): return self._stress_period.all().first()
[ "def", "stress_period", "(", "self", ")", ":", "return", "self", ".", "_stress_period", ".", "all", "(", ")", ".", "first", "(", ")" ]
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_modflow_modelinstance/models.py#L708-L709
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/studiomax/cachelib/transformcache.py
python
toggleCaches
( object, state )
return False
\remarks enables/disables the caches on the inputed object based on the given state \param object <Py3dsMax.mxs.Object> \param state <bool> \return <bool> success
\remarks enables/disables the caches on the inputed object based on the given state \param object <Py3dsMax.mxs.Object> \param state <bool> \return <bool> success
[ "\\", "remarks", "enables", "/", "disables", "the", "caches", "on", "the", "inputed", "object", "based", "on", "the", "given", "state", "\\", "param", "object", "<Py3dsMax", ".", "mxs", ".", "Object", ">", "\\", "param", "state", "<bool", ">", "\\", "ret...
def toggleCaches( object, state ): """ \remarks enables/disables the caches on the inputed object based on the given state \param object <Py3dsMax.mxs.Object> \param state <bool> \return <bool> success """ is_prop = mxs.isproperty classof = mxs.classof if ( is_prop( object, 'controller' ) and classof( object.controller ) == mxs.Transform_Cache ): control = object.controller if ( control.enabled != state ): control.enabled = not canDisableCaches( object ) and state return False
[ "def", "toggleCaches", "(", "object", ",", "state", ")", ":", "is_prop", "=", "mxs", ".", "isproperty", "classof", "=", "mxs", ".", "classof", "if", "(", "is_prop", "(", "object", ",", "'controller'", ")", "and", "classof", "(", "object", ".", "controlle...
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/studiomax/cachelib/transformcache.py#L70-L85
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
seahub/api2/views.py
python
RepoHistoryLimit.put
(self, request, repo_id, format=None)
[]
def put(self, request, repo_id, format=None): repo = seafile_api.get_repo(repo_id) if not repo: error_msg = 'Library %s not found.' % repo_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) # check permission if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo_id) else: repo_owner = seafile_api.get_repo_owner(repo_id) username = request.user.username # no settings for virtual repo if repo.is_virtual or not config.ENABLE_REPO_HISTORY_SETTING: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if '@seafile_group' in repo_owner: group_id = get_group_id_by_repo_owner(repo_owner) if not is_group_admin(group_id, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) else: if username != repo_owner: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check arg validation keep_days = request.data.get('keep_days', None) if not keep_days: error_msg = 'keep_days invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: keep_days = int(keep_days) except ValueError: error_msg = 'keep_days invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: # days <= -1, keep full history # days = 0, not keep history # days > 0, keep a period of days res = seafile_api.set_repo_history_limit(repo_id, keep_days) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) if res == 0: new_limit = seafile_api.get_repo_history_limit(repo_id) return Response({'keep_days': new_limit}) else: error_msg = 'Failed to set library history limit.' return api_error(status.HTTP_520_OPERATION_FAILED, error_msg)
[ "def", "put", "(", "self", ",", "request", ",", "repo_id", ",", "format", "=", "None", ")", ":", "repo", "=", "seafile_api", ".", "get_repo", "(", "repo_id", ")", "if", "not", "repo", ":", "error_msg", "=", "'Library %s not found.'", "%", "repo_id", "ret...
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/api2/views.py#L1494-L1550
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
whois_lambda/dns/rdatatype.py
python
from_text
(text)
return value
Convert text into a DNS rdata type value. @param text: the text @type text: string @raises dns.rdatatype.UnknownRdatatype: the type is unknown @raises ValueError: the rdata type value is not >= 0 and <= 65535 @rtype: int
Convert text into a DNS rdata type value.
[ "Convert", "text", "into", "a", "DNS", "rdata", "type", "value", "." ]
def from_text(text): """Convert text into a DNS rdata type value. @param text: the text @type text: string @raises dns.rdatatype.UnknownRdatatype: the type is unknown @raises ValueError: the rdata type value is not >= 0 and <= 65535 @rtype: int""" value = _by_text.get(text.upper()) if value is None: match = _unknown_type_pattern.match(text) if match is None: raise UnknownRdatatype value = int(match.group(1)) if value < 0 or value > 65535: raise ValueError("type must be between >= 0 and <= 65535") return value
[ "def", "from_text", "(", "text", ")", ":", "value", "=", "_by_text", ".", "get", "(", "text", ".", "upper", "(", ")", ")", "if", "value", "is", "None", ":", "match", "=", "_unknown_type_pattern", ".", "match", "(", "text", ")", "if", "match", "is", ...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/whois_lambda/dns/rdatatype.py#L202-L218
isce-framework/isce2
0e5114a8bede3caf1d533d98e44dfe4b983e3f48
components/isceobj/Planet/Planet.py
python
Planet.polar_axis
(self, vector)
return None
Give me a vector that is parallel to my spin axis
Give me a vector that is parallel to my spin axis
[ "Give", "me", "a", "vector", "that", "is", "parallel", "to", "my", "spin", "axis" ]
def polar_axis(self, vector): """Give me a vector that is parallel to my spin axis""" from isceobj.Util.geo.euclid import Vector if not isinstance(vector, Vector): try: vector = Vector(*vector) except Exception: raise ValueError( "polar axis must a Vector or length 3 container" ) pass self._polar_axis = vector.hat() return None
[ "def", "polar_axis", "(", "self", ",", "vector", ")", ":", "from", "isceobj", ".", "Util", ".", "geo", ".", "euclid", "import", "Vector", "if", "not", "isinstance", "(", "vector", ",", "Vector", ")", ":", "try", ":", "vector", "=", "Vector", "(", "*"...
https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/components/isceobj/Planet/Planet.py#L179-L191
lightforever/mlcomp
c78fdb77ec9c4ec8ff11beea50b90cab20903ad9
mlcomp/contrib/segmentation/deeplabv3/aspp.py
python
ASPP._init_weight
(self)
[]
def _init_weight(self): for m in self.modules(): if isinstance(m, nn.Conv2d): # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels # m.weight.data.normal_(0, math.sqrt(2. / n)) torch.nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
[ "def", "_init_weight", "(", "self", ")", ":", "for", "m", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "m", ",", "nn", ".", "Conv2d", ")", ":", "# n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels", "# m.weight.data.normal_(0, math....
https://github.com/lightforever/mlcomp/blob/c78fdb77ec9c4ec8ff11beea50b90cab20903ad9/mlcomp/contrib/segmentation/deeplabv3/aspp.py#L85-L93
chenguanyou/weixin_YiQi
ad86ed8061f4f5fa88b6600a9b0809e5bb3bfd08
backend/Yiqi/Yiqi/partyApp/xadmin/views/list.py
python
ListAdminView.get_list_display
(self)
return list(self.base_list_display)
Return a sequence containing the fields to be displayed on the list.
Return a sequence containing the fields to be displayed on the list.
[ "Return", "a", "sequence", "containing", "the", "fields", "to", "be", "displayed", "on", "the", "list", "." ]
def get_list_display(self): """ Return a sequence containing the fields to be displayed on the list. """ self.base_list_display = (COL_LIST_VAR in self.request.GET and self.request.GET[COL_LIST_VAR] != "" and \ self.request.GET[COL_LIST_VAR].split('.')) or self.list_display return list(self.base_list_display)
[ "def", "get_list_display", "(", "self", ")", ":", "self", ".", "base_list_display", "=", "(", "COL_LIST_VAR", "in", "self", ".", "request", ".", "GET", "and", "self", ".", "request", ".", "GET", "[", "COL_LIST_VAR", "]", "!=", "\"\"", "and", "self", ".",...
https://github.com/chenguanyou/weixin_YiQi/blob/ad86ed8061f4f5fa88b6600a9b0809e5bb3bfd08/backend/Yiqi/Yiqi/partyApp/xadmin/views/list.py#L148-L154
errbotio/errbot
66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d
errbot/core_plugins/utils.py
python
Utils.render_test
(self, _, args)
Tests / showcases the markdown rendering on your current backend
Tests / showcases the markdown rendering on your current backend
[ "Tests", "/", "showcases", "the", "markdown", "rendering", "on", "your", "current", "backend" ]
def render_test(self, _, args): """Tests / showcases the markdown rendering on your current backend""" with open(path.join(path.dirname(path.realpath(__file__)), "test.md")) as f: return f.read()
[ "def", "render_test", "(", "self", ",", "_", ",", "args", ")", ":", "with", "open", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "\"test.md\"", ")", ")", "as", "f", ":", "ret...
https://github.com/errbotio/errbot/blob/66e1de8e1d7daa62be7f9ed1b2ac8832f09fa25d/errbot/core_plugins/utils.py#L74-L77
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/idlelib/WidgetRedirector.py
python
WidgetRedirector.dispatch
(self, operation, *args)
Callback from Tcl which runs when the widget is referenced. If an operation has been registered in self._operations, apply the associated function to the args passed into Tcl. Otherwise, pass the operation through to Tk via the original Tcl function. Note that if a registered function is called, the operation is not passed through to Tk. Apply the function returned by self.register() to *args to accomplish that. For an example, see ColorDelegator.py.
Callback from Tcl which runs when the widget is referenced.
[ "Callback", "from", "Tcl", "which", "runs", "when", "the", "widget", "is", "referenced", "." ]
def dispatch(self, operation, *args): '''Callback from Tcl which runs when the widget is referenced. If an operation has been registered in self._operations, apply the associated function to the args passed into Tcl. Otherwise, pass the operation through to Tk via the original Tcl function. Note that if a registered function is called, the operation is not passed through to Tk. Apply the function returned by self.register() to *args to accomplish that. For an example, see ColorDelegator.py. ''' m = self._operations.get(operation) try: if m: return m(*args) else: return self.tk.call((self.orig, operation) + args) except TclError: return ""
[ "def", "dispatch", "(", "self", ",", "operation", ",", "*", "args", ")", ":", "m", "=", "self", ".", "_operations", ".", "get", "(", "operation", ")", "try", ":", "if", "m", ":", "return", "m", "(", "*", "args", ")", "else", ":", "return", "self"...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/idlelib/WidgetRedirector.py#L98-L117
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/fields.py
python
IPField.any2i
(self, pkt, x)
return self.h2i(pkt,x)
[]
def any2i(self, pkt, x): return self.h2i(pkt,x)
[ "def", "any2i", "(", "self", ",", "pkt", ",", "x", ")", ":", "return", "self", ".", "h2i", "(", "pkt", ",", "x", ")" ]
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/fields.py#L213-L214
Huangying-Zhan/DF-VO
6a2ec43fc6209d9058ae1709d779c5ada68a31f3
libs/deep_models/flow/deep_flow.py
python
DeepFlow.generate_images_pred_flow
(self, inputs, outputs)
return outputs
Generate the warped (reprojected) color images using optical flow for a minibatch. Generated images are saved into the `outputs` dictionary.
Generate the warped (reprojected) color images using optical flow for a minibatch. Generated images are saved into the `outputs` dictionary.
[ "Generate", "the", "warped", "(", "reprojected", ")", "color", "images", "using", "optical", "flow", "for", "a", "minibatch", ".", "Generated", "images", "are", "saved", "into", "the", "outputs", "dictionary", "." ]
def generate_images_pred_flow(self, inputs, outputs): """Generate the warped (reprojected) color images using optical flow for a minibatch. Generated images are saved into the `outputs` dictionary. """ source_scale = 0 for _, f_i in enumerate(self.frame_ids[1:]): if f_i != "s": for scale in self.flow_scales: # Warp image using forward flow flow = outputs[("flow", 0, f_i, scale)] # flow = self.resize_dense_flow(flow, self.height, self.width) # have been resized in inference() pix_coords = self.flow_to_pix(flow) outputs[("sample_flow", 0, f_i, scale)] = pix_coords outputs[("color_flow", 0, f_i, scale)] = F.grid_sample( inputs[("color", f_i, source_scale)], pix_coords, padding_mode="border") if self.flow_forward_backward: # Warp image using backward flow flow = outputs[("flow", f_i, 0, scale)] # flow = self.resize_dense_flow(flow, self.height, self.width) # have been resized in inference() pix_coords = self.flow_to_pix(flow) outputs[("sample_flow", f_i, 0, scale)] = pix_coords outputs[("color_flow", f_i, 0, scale)] = F.grid_sample( inputs[("color", 0, source_scale)], pix_coords, padding_mode="border") return outputs
[ "def", "generate_images_pred_flow", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "source_scale", "=", "0", "for", "_", ",", "f_i", "in", "enumerate", "(", "self", ".", "frame_ids", "[", "1", ":", "]", ")", ":", "if", "f_i", "!=", "\"s\"", ":...
https://github.com/Huangying-Zhan/DF-VO/blob/6a2ec43fc6209d9058ae1709d779c5ada68a31f3/libs/deep_models/flow/deep_flow.py#L254-L282
arsaboo/homeassistant-config
53c998986fbe84d793a0b174757154ab30e676e4
custom_components/alexa_media/sensor.py
python
AlexaMediaNotificationSensor.__init__
( self, client, n_dict, sensor_property: Text, account, name="Next Notification", icon=None, )
Initialize the Alexa sensor device.
Initialize the Alexa sensor device.
[ "Initialize", "the", "Alexa", "sensor", "device", "." ]
def __init__( self, client, n_dict, sensor_property: Text, account, name="Next Notification", icon=None, ): """Initialize the Alexa sensor device.""" # Class info self._client = client self._n_dict = n_dict self._sensor_property = sensor_property self._account = account self._dev_id = client.unique_id self._name = name self._unit = None self._device_class = DEVICE_CLASS_TIMESTAMP self._icon = icon self._all = [] self._active = [] self._next = None self._prior_value = None self._timestamp: Optional[datetime.datetime] = None self._tracker: Optional[Callable] = None self._state: Optional[datetime.datetime] = None
[ "def", "__init__", "(", "self", ",", "client", ",", "n_dict", ",", "sensor_property", ":", "Text", ",", "account", ",", "name", "=", "\"Next Notification\"", ",", "icon", "=", "None", ",", ")", ":", "# Class info", "self", ".", "_client", "=", "client", ...
https://github.com/arsaboo/homeassistant-config/blob/53c998986fbe84d793a0b174757154ab30e676e4/custom_components/alexa_media/sensor.py#L139-L165
mardix/assembly
4c993d19bc9d33c1641323e03231e9ecad711b38
assembly/_extensions.py
python
_Mailer.send
(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs)
To send email :param to: the recipients, list or string :param subject: the subject :param body: the body :param reply_to: reply_to :param template: template, will use the templates instead :param kwargs: context args :return: bool - True if everything is ok
To send email :param to: the recipients, list or string :param subject: the subject :param body: the body :param reply_to: reply_to :param template: template, will use the templates instead :param kwargs: context args :return: bool - True if everything is ok
[ "To", "send", "email", ":", "param", "to", ":", "the", "recipients", "list", "or", "string", ":", "param", "subject", ":", "the", "subject", ":", "param", "body", ":", "the", "body", ":", "param", "reply_to", ":", "reply_to", ":", "param", "template", ...
def send(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs): """ To send email :param to: the recipients, list or string :param subject: the subject :param body: the body :param reply_to: reply_to :param template: template, will use the templates instead :param kwargs: context args :return: bool - True if everything is ok """ sender = self.config.get("MAIL_SENDER") recipients = [to] if not isinstance(to, list) else to kwargs.update({ "subject": subject, "body": body, "reply_to": reply_to }) if not self.validated: raise Error("Mail configuration error") if self.provider == "SES": kwargs["to"] = recipients if template: self.mail.send_template(template=template, **kwargs) else: self.mail.send(**kwargs) elif self.provider == "SMTP": if template: data = self._template(template=template, **kwargs) kwargs["subject"] = data["subject"] kwargs["body"] = data["body"] kwargs["recipients"] = recipients kwargs["sender"] = sender # Remove invalid Messages keys _safe_keys = ["recipients", "subject", "body", "html", "alts", "cc", "bcc", "attachments", "reply_to", "sender", "date", "charset", "extra_headers", "mail_options", "rcpt_options"] for k in kwargs.copy(): if k not in _safe_keys: del kwargs[k] message = flask_mail.Message(**kwargs) self.mail.send(message) else: raise Error("Invalid mail provider. Must be 'SES' or 'SMTP'")
[ "def", "send", "(", "self", ",", "to", ",", "subject", "=", "None", ",", "body", "=", "None", ",", "reply_to", "=", "None", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sender", "=", "self", ".", "config", ".", "get", "(", ...
https://github.com/mardix/assembly/blob/4c993d19bc9d33c1641323e03231e9ecad711b38/assembly/_extensions.py#L181-L230
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/gui/gui_common.py
python
GuiCommon.__init__
(self, **kwds)
fmt_order, html_logging, inputs, parent=None,
fmt_order, html_logging, inputs, parent=None,
[ "fmt_order", "html_logging", "inputs", "parent", "=", "None" ]
def __init__(self, **kwds): """ fmt_order, html_logging, inputs, parent=None, """ # this will reset the background color/label color if things break #super(QMainWindow, self).__init__(self) if qt_version == 'pyqt5': super(GuiCommon, self).__init__(**kwds) elif qt_version == 'pyside2': QMainWindow.__init__(self) GuiVTKCommon.__init__(self, **kwds) else: #: pragma: no cover raise NotImplementedError(qt_version) self.format_class_map = CLASS_MAP fmt_order = kwds['fmt_order'] inputs = kwds['inputs'] #self.app = inputs['app'] #del inputs['app'] if inputs['log'] is not None: html_logging = False else: html_logging = kwds['html_logging'] del kwds['html_logging'] #----------------------------------------------------------------------- self._active_background_image = None self.reset_settings = False self.fmts = fmt_order self.base_window_title = f'pyNastran v{pyNastran.__version__}' #defaults self.wildcard_delimited = 'Delimited Text (*.txt; *.dat; *.csv)' # initializes tools/checkables self.set_tools() self.html_logging = html_logging self.execute_python = True self.scalar_bar = ScalarBar(self.legend_obj.is_horizontal_scalar_bar) # in,lb,s self.input_units = ['', '', ''] # '' means not set self.display_units = ['', '', '']
[ "def", "__init__", "(", "self", ",", "*", "*", "kwds", ")", ":", "# this will reset the background color/label color if things break", "#super(QMainWindow, self).__init__(self)", "if", "qt_version", "==", "'pyqt5'", ":", "super", "(", "GuiCommon", ",", "self", ")", ".",...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/gui/gui_common.py#L64-L110
daiquocnguyen/Graph-Transformer
f9dc818a06ff0490f3d1bcc2e7b9ccd188950dcd
UGformerV1_TF/universal_transformer_modified.py
python
update_hparams_for_universal_transformer
(hparams)
return hparams
Adds deault hparams for all of the variants of the Universal Transformer. Args: hparams: default hparams (usually one of the standard hparams from transformer model (like "transformer_base") Returns: hparams with default values for Universal Transformers hyper-parameters
Adds deault hparams for all of the variants of the Universal Transformer.
[ "Adds", "deault", "hparams", "for", "all", "of", "the", "variants", "of", "the", "Universal", "Transformer", "." ]
def update_hparams_for_universal_transformer(hparams): """Adds deault hparams for all of the variants of the Universal Transformer. Args: hparams: default hparams (usually one of the standard hparams from transformer model (like "transformer_base") Returns: hparams with default values for Universal Transformers hyper-parameters """ hparams.daisy_chain_variables = False # Breaks multi-gpu in while loops. # If not None, mixes vanilla transformer with Universal Transformer. # Options: None, "before_ut", and "after_ut". hparams.add_hparam("mix_with_transformer", None) # Number of vanilla transformer layers used to be mixed with u-transofmer. hparams.add_hparam("num_mixedin_layers", 2) # Type of recurrency: # basic, highway, skip, dwa, act, rnn, gru, lstm. hparams.add_hparam("recurrence_type", "basic") # Number of steps (which is equivalent to num layer in transformer). hparams.add_hparam("num_rec_steps", hparams.num_hidden_layers) # Add the positional mebedding at each step(horisontal timing) hparams.add_hparam("add_position_timing_signal", True) if hparams.add_position_timing_signal: hparams.pos = None # Logic of position shifting when using timing signal: # None, "random", "step" hparams.add_hparam("position_start_index", None) # Add an step embedding at each step (vertical timing) hparams.add_hparam("add_step_timing_signal", True) # Either "learned" or "sinusoid" hparams.add_hparam("step_timing_signal_type", "learned") # Add or concat the timing signal (applied both on position and step timing). # Options: "add" and "concat". hparams.add_hparam("add_or_concat_timing_signal", "add") # Add SRU at the beginning of each Universal Transformer step. # This can be considered as a position timing signal hparams.add_hparam("add_sru", False) # Default ffn layer is separable convolution. # Options: "fc" and "sepconv". hparams.add_hparam("transformer_ffn_type", "fc") # Transform bias (in models with highway or skip connection). hparams.add_hparam("transform_bias_init", -1.0) hparams.add_hparam("couple_carry_transform_gates", True) # Depth-wise attention (grid-transformer!) hparams: # Adds depth embedding, if true. hparams.add_hparam("depth_embedding", True) # Learns attention weights for elements (instead of positions), if true. hparams.add_hparam("dwa_elements", True) # Type of ffn_layer used for gate in skip, highway, etc. # "dense" or "dense_dropconnect". # With dense_relu_dense, the bias/kernel initializations will not be applied. hparams.add_hparam("gate_ffn_layer", "dense") # LSTM forget bias for lstm style recurrence. hparams.add_hparam("lstm_forget_bias", 1.0) # Uses the memory at the last step as the final output, if true. hparams.add_hparam("use_memory_as_final_state", True) # if also add a ffn unit to the transition function when using gru/lstm hparams.add_hparam("add_ffn_unit_to_the_transition_function", False) # Type of act: basic/accumulated/global (instead of position-wise!)/random. hparams.add_hparam("act_type", "basic") # Max number of steps (forces halting at this step). hparams.add_hparam("act_max_steps", 2 * hparams.num_hidden_layers) hparams.add_hparam("act_halting_bias_init", 1.0) hparams.add_hparam("act_epsilon", 0.01) hparams.add_hparam("act_loss_weight", 0.01) return hparams
[ "def", "update_hparams_for_universal_transformer", "(", "hparams", ")", ":", "hparams", ".", "daisy_chain_variables", "=", "False", "# Breaks multi-gpu in while loops.", "# If not None, mixes vanilla transformer with Universal Transformer.", "# Options: None, \"before_ut\", and \"after_ut\...
https://github.com/daiquocnguyen/Graph-Transformer/blob/f9dc818a06ff0490f3d1bcc2e7b9ccd188950dcd/UGformerV1_TF/universal_transformer_modified.py#L349-L431
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/cookielib.py
python
unmatched
(match)
return match.string[:start]+match.string[end:]
Return unmatched part of re.Match object.
Return unmatched part of re.Match object.
[ "Return", "unmatched", "part", "of", "re", ".", "Match", "object", "." ]
def unmatched(match): """Return unmatched part of re.Match object.""" start, end = match.span(0) return match.string[:start]+match.string[end:]
[ "def", "unmatched", "(", "match", ")", ":", "start", ",", "end", "=", "match", ".", "span", "(", "0", ")", "return", "match", ".", "string", "[", ":", "start", "]", "+", "match", ".", "string", "[", "end", ":", "]" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/cookielib.py#L317-L320
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/inspect.py
python
getmembers
(object, predicate=None)
return results
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
[ "Return", "all", "members", "of", "an", "object", "as", "(", "name", "value", ")", "pairs", "sorted", "by", "name", ".", "Optionally", "only", "return", "members", "that", "satisfy", "a", "given", "predicate", "." ]
def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError: continue if not predicate or predicate(value): results.append((key, value)) results.sort() return results
[ "def", "getmembers", "(", "object", ",", "predicate", "=", "None", ")", ":", "results", "=", "[", "]", "for", "key", "in", "dir", "(", "object", ")", ":", "try", ":", "value", "=", "getattr", "(", "object", ",", "key", ")", "except", "AttributeError"...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/inspect.py#L247-L259
niosus/EasyClangComplete
3b16eb17735aaa3f56bb295fc5481b269ee9f2ef
plugin/clang/cindex33.py
python
Token.spelling
(self)
return conf.lib.clang_getTokenSpelling(self._tu, self)
The spelling of this token. This is the textual representation of the token in source.
The spelling of this token.
[ "The", "spelling", "of", "this", "token", "." ]
def spelling(self): """The spelling of this token. This is the textual representation of the token in source. """ return conf.lib.clang_getTokenSpelling(self._tu, self)
[ "def", "spelling", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTokenSpelling", "(", "self", ".", "_tu", ",", "self", ")" ]
https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex33.py#L2509-L2514
python-attrs/cattrs
50ba769c8349f5891b157d2bb7f06602822ac0a3
src/cattr/converters.py
python
Converter._structure_dict
(self, obj, cl)
Convert a mapping into a potentially generic dict.
Convert a mapping into a potentially generic dict.
[ "Convert", "a", "mapping", "into", "a", "potentially", "generic", "dict", "." ]
def _structure_dict(self, obj, cl): """Convert a mapping into a potentially generic dict.""" if is_bare(cl) or cl.__args__ == (Any, Any): return dict(obj) else: key_type, val_type = cl.__args__ if key_type is Any: val_conv = self._structure_func.dispatch(val_type) return {k: val_conv(v, val_type) for k, v in obj.items()} elif val_type is Any: key_conv = self._structure_func.dispatch(key_type) return {key_conv(k, key_type): v for k, v in obj.items()} else: key_conv = self._structure_func.dispatch(key_type) val_conv = self._structure_func.dispatch(val_type) return { key_conv(k, key_type): val_conv(v, val_type) for k, v in obj.items() }
[ "def", "_structure_dict", "(", "self", ",", "obj", ",", "cl", ")", ":", "if", "is_bare", "(", "cl", ")", "or", "cl", ".", "__args__", "==", "(", "Any", ",", "Any", ")", ":", "return", "dict", "(", "obj", ")", "else", ":", "key_type", ",", "val_ty...
https://github.com/python-attrs/cattrs/blob/50ba769c8349f5891b157d2bb7f06602822ac0a3/src/cattr/converters.py#L503-L521
cagbal/ros_people_object_detection_tensorflow
982ffd4a54b8059638f5cd4aa167299c7fc9e61f
src/object_detection/metrics/tf_example_parser.py
python
BoundingBoxParser.__init__
(self, xmin_field_name, ymin_field_name, xmax_field_name, ymax_field_name)
[]
def __init__(self, xmin_field_name, ymin_field_name, xmax_field_name, ymax_field_name): self.field_names = [ ymin_field_name, xmin_field_name, ymax_field_name, xmax_field_name ]
[ "def", "__init__", "(", "self", ",", "xmin_field_name", ",", "ymin_field_name", ",", "xmax_field_name", ",", "ymax_field_name", ")", ":", "self", ".", "field_names", "=", "[", "ymin_field_name", ",", "xmin_field_name", ",", "ymax_field_name", ",", "xmax_field_name",...
https://github.com/cagbal/ros_people_object_detection_tensorflow/blob/982ffd4a54b8059638f5cd4aa167299c7fc9e61f/src/object_detection/metrics/tf_example_parser.py#L68-L72
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/pyparsing/core.py
python
ParserElement.__rmul__
(self, other)
return self.__mul__(other)
[]
def __rmul__(self, other): return self.__mul__(other)
[ "def", "__rmul__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "__mul__", "(", "other", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/pyparsing/core.py#L1509-L1510
conda/conda-build
2a19925f2b2ca188f80ffa625cd783e7d403793f
versioneer.py
python
versions_from_parentdir
(parentdir_prefix, root, verbose)
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
Try to determine the version from the parent directory name.
[ "Try", "to", "determine", "the", "version", "from", "the", "parent", "directory", "name", "." ]
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
[ "def", "versions_from_parentdir", "(", "parentdir_prefix", ",", "root", ",", "verbose", ")", ":", "rootdirs", "=", "[", "]", "for", "i", "in", "range", "(", "3", ")", ":", "dirname", "=", "os", ".", "path", ".", "basename", "(", "root", ")", "if", "d...
https://github.com/conda/conda-build/blob/2a19925f2b2ca188f80ffa625cd783e7d403793f/versioneer.py#L1158-L1180
runawayhorse001/LearningApacheSpark
67f3879dce17553195f094f5728b94a01badcf24
pyspark/sql/context.py
python
SQLContext.getOrCreate
(cls, sc)
return cls._instantiatedContext
Get the existing SQLContext or create a new one with given SparkContext. :param sc: SparkContext
Get the existing SQLContext or create a new one with given SparkContext.
[ "Get", "the", "existing", "SQLContext", "or", "create", "a", "new", "one", "with", "given", "SparkContext", "." ]
def getOrCreate(cls, sc): """ Get the existing SQLContext or create a new one with given SparkContext. :param sc: SparkContext """ if cls._instantiatedContext is None: jsqlContext = sc._jvm.SQLContext.getOrCreate(sc._jsc.sc()) sparkSession = SparkSession(sc, jsqlContext.sparkSession()) cls(sc, sparkSession, jsqlContext) return cls._instantiatedContext
[ "def", "getOrCreate", "(", "cls", ",", "sc", ")", ":", "if", "cls", ".", "_instantiatedContext", "is", "None", ":", "jsqlContext", "=", "sc", ".", "_jvm", ".", "SQLContext", ".", "getOrCreate", "(", "sc", ".", "_jsc", ".", "sc", "(", ")", ")", "spark...
https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/sql/context.py#L103-L113
onaio/onadata
89ad16744e8f247fb748219476f6ac295869a95f
onadata/libs/utils/viewer_tools.py
python
image_urls_for_form
(xform)
return sum( [ image_urls(s) for s in xform.instances.filter(deleted_at__isnull=True) ], [])
Return image urls of all image attachments of the xform.
Return image urls of all image attachments of the xform.
[ "Return", "image", "urls", "of", "all", "image", "attachments", "of", "the", "xform", "." ]
def image_urls_for_form(xform): """Return image urls of all image attachments of the xform.""" return sum( [ image_urls(s) for s in xform.instances.filter(deleted_at__isnull=True) ], [])
[ "def", "image_urls_for_form", "(", "xform", ")", ":", "return", "sum", "(", "[", "image_urls", "(", "s", ")", "for", "s", "in", "xform", ".", "instances", ".", "filter", "(", "deleted_at__isnull", "=", "True", ")", "]", ",", "[", "]", ")" ]
https://github.com/onaio/onadata/blob/89ad16744e8f247fb748219476f6ac295869a95f/onadata/libs/utils/viewer_tools.py#L30-L36
stepjam/PyRep
d778d5d4ffa3be366d4e699f6e2941553fd47ecc
pyrep/robots/mobiles/nonholonomic_base.py
python
NonHolonomicBase.get_base_velocities
(self)
return [lv, av]
Gets linear and angular velocities of the mobile robot base calculated from kinematics equations. Left joint should have index 1, right joint should have index. :return: A list with linear and angular velocity of the robot base.
Gets linear and angular velocities of the mobile robot base calculated from kinematics equations. Left joint should have index 1, right joint should have index.
[ "Gets", "linear", "and", "angular", "velocities", "of", "the", "mobile", "robot", "base", "calculated", "from", "kinematics", "equations", ".", "Left", "joint", "should", "have", "index", "1", "right", "joint", "should", "have", "index", "." ]
def get_base_velocities(self) -> List[float]: """Gets linear and angular velocities of the mobile robot base calculated from kinematics equations. Left joint should have index 1, right joint should have index. :return: A list with linear and angular velocity of the robot base. """ wv = self.get_joint_velocities() lv = sum(wv) * self.wheel_radius / 2.0 v_diff = wv[1] - wv[0] av = self.wheel_radius * v_diff / self.wheel_distance return [lv, av]
[ "def", "get_base_velocities", "(", "self", ")", "->", "List", "[", "float", "]", ":", "wv", "=", "self", ".", "get_joint_velocities", "(", ")", "lv", "=", "sum", "(", "wv", ")", "*", "self", ".", "wheel_radius", "/", "2.0", "v_diff", "=", "wv", "[", ...
https://github.com/stepjam/PyRep/blob/d778d5d4ffa3be366d4e699f6e2941553fd47ecc/pyrep/robots/mobiles/nonholonomic_base.py#L36-L49
X-Plane/XPlane2Blender
5face69fbb828a414b167dcb063fabf5182a54bc
io_xplane2blender/xplane_types/xplane_material.py
python
XPlaneMaterial.isValid
(self, exportType:str)
return io_xplane2blender.xplane_types.xplane_material_utils.validate(self, exportType)
# Method: isValid # Checks if material is valid based on an export type. # # Parameters: # exportType <string> - one of "aircraft", "cockpit", "scenery", "instanced_scenery" # # Returns: # Tuple[List[str],Liststr]] A tuple of a list of errors and a list of warnings # bool, list - True if Material is valid, else False + a list of errors
# Method: isValid # Checks if material is valid based on an export type. # # Parameters: # exportType <string> - one of "aircraft", "cockpit", "scenery", "instanced_scenery" # # Returns: # Tuple[List[str],Liststr]] A tuple of a list of errors and a list of warnings # bool, list - True if Material is valid, else False + a list of errors
[ "#", "Method", ":", "isValid", "#", "Checks", "if", "material", "is", "valid", "based", "on", "an", "export", "type", ".", "#", "#", "Parameters", ":", "#", "exportType", "<string", ">", "-", "one", "of", "aircraft", "cockpit", "scenery", "instanced_scener...
def isValid(self, exportType:str)->Tuple[List[str],List[str]]: ''' # Method: isValid # Checks if material is valid based on an export type. # # Parameters: # exportType <string> - one of "aircraft", "cockpit", "scenery", "instanced_scenery" # # Returns: # Tuple[List[str],Liststr]] A tuple of a list of errors and a list of warnings # bool, list - True if Material is valid, else False + a list of errors ''' return io_xplane2blender.xplane_types.xplane_material_utils.validate(self, exportType)
[ "def", "isValid", "(", "self", ",", "exportType", ":", "str", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", ":", "return", "io_xplane2blender", ".", "xplane_types", ".", "xplane_material_utils", ".", "validate", "("...
https://github.com/X-Plane/XPlane2Blender/blob/5face69fbb828a414b167dcb063fabf5182a54bc/io_xplane2blender/xplane_types/xplane_material.py#L242-L254
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/decimal.py
python
Context.__repr__
(self)
return ', '.join(s) + ')'
Show the current context.
Show the current context.
[ "Show", "the", "current", "context", "." ]
def __repr__(self): """Show the current context.""" s = [] s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self)) names = [f.__name__ for f, v in self.flags.items() if v] s.append('flags=[' + ', '.join(names) + ']') names = [t.__name__ for t, v in self.traps.items() if v] s.append('traps=[' + ', '.join(names) + ']') return ', '.join(s) + ')'
[ "def", "__repr__", "(", "self", ")", ":", "s", "=", "[", "]", "s", ".", "append", "(", "'Context(prec=%(prec)d, rounding=%(rounding)s, '", "'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'", "%", "vars", "(", "self", ")", ")", "names", "=", "[", "f", ".", "...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/decimal.py#L3792-L3802
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/graphgym/checkpoint.py
python
get_ckpt_dir
()
return osp.join(cfg.run_dir, 'ckpt')
[]
def get_ckpt_dir() -> str: return osp.join(cfg.run_dir, 'ckpt')
[ "def", "get_ckpt_dir", "(", ")", "->", "str", ":", "return", "osp", ".", "join", "(", "cfg", ".", "run_dir", ",", "'ckpt'", ")" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/graphgym/checkpoint.py#L71-L72
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/Pillow-6.0.0-py3.7-macosx-10.9-x86_64.egg/PIL/Image.py
python
open
(fp, mode="r")
Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the :py:meth:`~PIL.Image.Image.load` method). See :py:func:`~PIL.Image.new`. See :ref:`file-handling`. :param fp: A filename (string), pathlib.Path object or a file object. The file object must implement :py:meth:`~file.read`, :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods, and be opened in binary mode. :param mode: The mode. If given, this argument must be "r". :returns: An :py:class:`~PIL.Image.Image` object. :exception IOError: If the file cannot be found, or the image cannot be opened and identified.
Opens and identifies the given image file.
[ "Opens", "and", "identifies", "the", "given", "image", "file", "." ]
def open(fp, mode="r"): """ Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the :py:meth:`~PIL.Image.Image.load` method). See :py:func:`~PIL.Image.new`. See :ref:`file-handling`. :param fp: A filename (string), pathlib.Path object or a file object. The file object must implement :py:meth:`~file.read`, :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods, and be opened in binary mode. :param mode: The mode. If given, this argument must be "r". :returns: An :py:class:`~PIL.Image.Image` object. :exception IOError: If the file cannot be found, or the image cannot be opened and identified. """ if mode != "r": raise ValueError("bad mode %r" % mode) exclusive_fp = False filename = "" if isPath(fp): filename = fp elif HAS_PATHLIB and isinstance(fp, Path): filename = str(fp.resolve()) if filename: fp = builtins.open(filename, "rb") exclusive_fp = True try: fp.seek(0) except (AttributeError, io.UnsupportedOperation): fp = io.BytesIO(fp.read()) exclusive_fp = True prefix = fp.read(16) preinit() accept_warnings = [] def _open_core(fp, filename, prefix): for i in ID: try: factory, accept = OPEN[i] result = not accept or accept(prefix) if type(result) in [str, bytes]: accept_warnings.append(result) elif result: fp.seek(0) im = factory(fp, filename) _decompression_bomb_check(im.size) return im except (SyntaxError, IndexError, TypeError, struct.error): # Leave disabled by default, spams the logs with image # opening failures that are entirely expected. # logger.debug("", exc_info=True) continue except BaseException: if exclusive_fp: fp.close() raise return None im = _open_core(fp, filename, prefix) if im is None: if init(): im = _open_core(fp, filename, prefix) if im: im._exclusive_fp = exclusive_fp return im if exclusive_fp: fp.close() for message in accept_warnings: warnings.warn(message) raise IOError("cannot identify image file %r" % (filename if filename else fp))
[ "def", "open", "(", "fp", ",", "mode", "=", "\"r\"", ")", ":", "if", "mode", "!=", "\"r\"", ":", "raise", "ValueError", "(", "\"bad mode %r\"", "%", "mode", ")", "exclusive_fp", "=", "False", "filename", "=", "\"\"", "if", "isPath", "(", "fp", ")", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/Pillow-6.0.0-py3.7-macosx-10.9-x86_64.egg/PIL/Image.py#L2621-L2705
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/wsgiserver/wsgiserver2.py
python
SizeCheckWrapper.next
(self)
return data
[]
def next(self): data = self.rfile.next() self.bytes_read += len(data) self._check_length() return data
[ "def", "next", "(", "self", ")", ":", "data", "=", "self", ".", "rfile", ".", "next", "(", ")", "self", ".", "bytes_read", "+=", "len", "(", "data", ")", "self", ".", "_check_length", "(", ")", "return", "data" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/wsgiserver/wsgiserver2.py#L336-L340
spotify/luigi
c3b66f4a5fa7eaa52f9a72eb6704b1049035c789
examples/top_artists.py
python
Streams.run
(self)
Generates bogus data and writes it into the :py:meth:`~.Streams.output` target.
Generates bogus data and writes it into the :py:meth:`~.Streams.output` target.
[ "Generates", "bogus", "data", "and", "writes", "it", "into", "the", ":", "py", ":", "meth", ":", "~", ".", "Streams", ".", "output", "target", "." ]
def run(self): """ Generates bogus data and writes it into the :py:meth:`~.Streams.output` target. """ with self.output().open('w') as output: for _ in range(1000): output.write('{} {} {}\n'.format( random.randint(0, 999), random.randint(0, 999), random.randint(0, 999)))
[ "def", "run", "(", "self", ")", ":", "with", "self", ".", "output", "(", ")", ".", "open", "(", "'w'", ")", "as", "output", ":", "for", "_", "in", "range", "(", "1000", ")", ":", "output", ".", "write", "(", "'{} {} {}\\n'", ".", "format", "(", ...
https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/examples/top_artists.py#L54-L63
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/sqlalchemy/dialects/mssql/base.py
python
MSExecutionContext.pre_exec
(self)
Activate IDENTITY_INSERT if needed.
Activate IDENTITY_INSERT if needed.
[ "Activate", "IDENTITY_INSERT", "if", "needed", "." ]
def pre_exec(self): """Activate IDENTITY_INSERT if needed.""" if self.isinsert: tbl = self.compiled.statement.table seq_column = tbl._autoincrement_column insert_has_sequence = seq_column is not None if insert_has_sequence: self._enable_identity_insert = \ seq_column.key in self.compiled_parameters[0] or \ ( self.compiled.statement.parameters and ( ( self.compiled.statement._has_multi_parameters and seq_column.key in self.compiled.statement.parameters[0] ) or ( not self.compiled.statement._has_multi_parameters and seq_column.key in self.compiled.statement.parameters ) ) ) else: self._enable_identity_insert = False self._select_lastrowid = insert_has_sequence and \ not self.compiled.returning and \ not self._enable_identity_insert and \ not self.executemany if self._enable_identity_insert: self.root_connection._cursor_execute( self.cursor, self._opt_encode( "SET IDENTITY_INSERT %s ON" % self.dialect.identifier_preparer.format_table(tbl)), (), self)
[ "def", "pre_exec", "(", "self", ")", ":", "if", "self", ".", "isinsert", ":", "tbl", "=", "self", ".", "compiled", ".", "statement", ".", "table", "seq_column", "=", "tbl", ".", "_autoincrement_column", "insert_has_sequence", "=", "seq_column", "is", "not", ...
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/sqlalchemy/dialects/mssql/base.py#L995-L1037
mkusner/grammarVAE
ffffe272a8cf1772578dfc92254c55c224cddc02
equation_optimization/simulation1/grammar/run_bo.py
python
save_object
(obj, filename)
Function that saves an object to a file using pickle
Function that saves an object to a file using pickle
[ "Function", "that", "saves", "an", "object", "to", "a", "file", "using", "pickle" ]
def save_object(obj, filename): """ Function that saves an object to a file using pickle """ result = pickle.dumps(obj) with gzip.GzipFile(filename, 'wb') as dest: dest.write(result) dest.close()
[ "def", "save_object", "(", "obj", ",", "filename", ")", ":", "result", "=", "pickle", ".", "dumps", "(", "obj", ")", "with", "gzip", ".", "GzipFile", "(", "filename", ",", "'wb'", ")", "as", "dest", ":", "dest", ".", "write", "(", "result", ")", "d...
https://github.com/mkusner/grammarVAE/blob/ffffe272a8cf1772578dfc92254c55c224cddc02/equation_optimization/simulation1/grammar/run_bo.py#L58-L66
djblets/djblets
0496e1ec49e43d43d776768c9fc5b6f8af56ec2c
djblets/db/fields/json_field.py
python
JSONField.to_python
(self, value)
return value
Return a value suitable for using in Python code. This will return the deserialized version of the data, allowing Python code to work with the data directly. Args: value (object): The value to make usable in Python code. Returns: object: The deserialized data.
Return a value suitable for using in Python code.
[ "Return", "a", "value", "suitable", "for", "using", "in", "Python", "code", "." ]
def to_python(self, value): """Return a value suitable for using in Python code. This will return the deserialized version of the data, allowing Python code to work with the data directly. Args: value (object): The value to make usable in Python code. Returns: object: The deserialized data. """ if isinstance(value, six.string_types): value = self.loads(value) return value
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "self", ".", "loads", "(", "value", ")", "return", "value" ]
https://github.com/djblets/djblets/blob/0496e1ec49e43d43d776768c9fc5b6f8af56ec2c/djblets/db/fields/json_field.py#L315-L332
redhat-imaging/imagefactory
176f6e045e1df049d50f33a924653128d5ab8b27
imgfac/rest/bottle.py
python
BaseResponse.set_header
(self, name, value)
Create a new response header, replacing any previously defined headers with the same name.
Create a new response header, replacing any previously defined headers with the same name.
[ "Create", "a", "new", "response", "header", "replacing", "any", "previously", "defined", "headers", "with", "the", "same", "name", "." ]
def set_header(self, name, value): ''' Create a new response header, replacing any previously defined headers with the same name. ''' self._headers[_hkey(name)] = [_hval(value)]
[ "def", "set_header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_headers", "[", "_hkey", "(", "name", ")", "]", "=", "[", "_hval", "(", "value", ")", "]" ]
https://github.com/redhat-imaging/imagefactory/blob/176f6e045e1df049d50f33a924653128d5ab8b27/imgfac/rest/bottle.py#L1544-L1547
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/packages/urllib3/connection.py
python
_match_hostname
(cert, asserted_hostname)
[]
def _match_hostname(cert, asserted_hostname): try: match_hostname(cert, asserted_hostname) except CertificateError as e: log.error( 'Certificate did not match expected hostname: %s. ' 'Certificate: %s', asserted_hostname, cert ) # Add cert to exception and reraise so client code can inspect # the cert when catching the exception, if they want to e._peer_cert = cert raise
[ "def", "_match_hostname", "(", "cert", ",", "asserted_hostname", ")", ":", "try", ":", "match_hostname", "(", "cert", ",", "asserted_hostname", ")", "except", "CertificateError", "as", "e", ":", "log", ".", "error", "(", "'Certificate did not match expected hostname...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/packages/urllib3/connection.py#L311-L322
frePPLe/frepple
57aa612030b4fcd03cb9c613f83a7dac4f0e8d6d
freppledb/common/report.py
python
GridReport._filter_in
(query, reportrow, data, database=DEFAULT_DB_ALIAS)
[]
def _filter_in(query, reportrow, data, database=DEFAULT_DB_ALIAS): if isinstance(reportrow, GridFieldChoice): # Comparison also with the translated choices accepted = [] for f in smart_str(data).split(","): t = f.strip().lower() for c in reportrow.choices: if t in (c[0].lower(), force_str(c[1]).lower()): accepted.append(c[0]) return models.Q(**{"%s__in" % reportrow.field_name: accepted}) else: return models.Q( **{"%s__in" % reportrow.field_name: smart_str(data).strip().split(",")} )
[ "def", "_filter_in", "(", "query", ",", "reportrow", ",", "data", ",", "database", "=", "DEFAULT_DB_ALIAS", ")", ":", "if", "isinstance", "(", "reportrow", ",", "GridFieldChoice", ")", ":", "# Comparison also with the translated choices", "accepted", "=", "[", "]"...
https://github.com/frePPLe/frepple/blob/57aa612030b4fcd03cb9c613f83a7dac4f0e8d6d/freppledb/common/report.py#L2546-L2559
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/httplib.py
python
HTTPResponse._safe_read
(self, amt)
return ''.join(s)
Read the number of bytes requested, compensating for partial reads. Normally, we have a blocking socket, but a read() can be interrupted by a signal (resulting in a partial read). Note that we cannot distinguish between EOF and an interrupt when zero bytes have been read. IncompleteRead() will be raised in this situation. This function should be used when <amt> bytes "should" be present for reading. If the bytes are truly not available (due to EOF), then the IncompleteRead exception can be used to detect the problem.
Read the number of bytes requested, compensating for partial reads.
[ "Read", "the", "number", "of", "bytes", "requested", "compensating", "for", "partial", "reads", "." ]
def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads. Normally, we have a blocking socket, but a read() can be interrupted by a signal (resulting in a partial read). Note that we cannot distinguish between EOF and an interrupt when zero bytes have been read. IncompleteRead() will be raised in this situation. This function should be used when <amt> bytes "should" be present for reading. If the bytes are truly not available (due to EOF), then the IncompleteRead exception can be used to detect the problem. """ # NOTE(gps): As of svn r74426 socket._fileobject.read(x) will never # return less than x bytes unless EOF is encountered. It now handles # signal interruptions (socket.error EINTR) internally. This code # never caught that exception anyways. It seems largely pointless. # self.fp.read(amt) will work fine. s = [] while amt > 0: chunk = self.fp.read(min(amt, MAXAMOUNT)) if not chunk: raise IncompleteRead(''.join(s), amt) s.append(chunk) amt -= len(chunk) return ''.join(s)
[ "def", "_safe_read", "(", "self", ",", "amt", ")", ":", "# NOTE(gps): As of svn r74426 socket._fileobject.read(x) will never", "# return less than x bytes unless EOF is encountered. It now handles", "# signal interruptions (socket.error EINTR) internally. This code", "# never caught that exc...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/httplib.py#L667-L693
Sceptre/sceptre
b44797ae712e1e57c2421f2d93c35a4e8104c5ee
sceptre/diffing/stack_differ.py
python
repr_str
(dumper: Dumper, data: str)
return dumper.represent_str(data)
A YAML Representer that handles strings, breaking multi-line strings into something a lot more readable in the yaml output. This is useful for representing long, multiline strings in templates or in stack parameters. :param dumper: The Dumper that is being used to serialize this object :param data: The string to serialize :return: The represented string
A YAML Representer that handles strings, breaking multi-line strings into something a lot more readable in the yaml output. This is useful for representing long, multiline strings in templates or in stack parameters.
[ "A", "YAML", "Representer", "that", "handles", "strings", "breaking", "multi", "-", "line", "strings", "into", "something", "a", "lot", "more", "readable", "in", "the", "yaml", "output", ".", "This", "is", "useful", "for", "representing", "long", "multiline", ...
def repr_str(dumper: Dumper, data: str) -> str: """A YAML Representer that handles strings, breaking multi-line strings into something a lot more readable in the yaml output. This is useful for representing long, multiline strings in templates or in stack parameters. :param dumper: The Dumper that is being used to serialize this object :param data: The string to serialize :return: The represented string """ if '\n' in data: return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|') return dumper.represent_str(data)
[ "def", "repr_str", "(", "dumper", ":", "Dumper", ",", "data", ":", "str", ")", "->", "str", ":", "if", "'\\n'", "in", "data", ":", "return", "dumper", ".", "represent_scalar", "(", "u'tag:yaml.org,2002:str'", ",", "data", ",", "style", "=", "'|'", ")", ...
https://github.com/Sceptre/sceptre/blob/b44797ae712e1e57c2421f2d93c35a4e8104c5ee/sceptre/diffing/stack_differ.py#L41-L52
getsentry/sentry-python
f92e9707ea73765eb9fdcf6482dc46aed4221a7a
sentry_sdk/scope.py
python
Scope.fingerprint
(self, value)
When set this overrides the default fingerprint.
When set this overrides the default fingerprint.
[ "When", "set", "this", "overrides", "the", "default", "fingerprint", "." ]
def fingerprint(self, value): # type: (Optional[List[str]]) -> None """When set this overrides the default fingerprint.""" self._fingerprint = value
[ "def", "fingerprint", "(", "self", ",", "value", ")", ":", "# type: (Optional[List[str]]) -> None", "self", ".", "_fingerprint", "=", "value" ]
https://github.com/getsentry/sentry-python/blob/f92e9707ea73765eb9fdcf6482dc46aed4221a7a/sentry_sdk/scope.py#L138-L141
apple/coremltools
141a83af482fcbdd5179807c9eaff9a7999c2c49
coremltools/models/neural_network/builder.py
python
_get_lstm_weight_fields
(lstm_wp)
return [ lstm_wp.inputGateWeightMatrix, lstm_wp.forgetGateWeightMatrix, lstm_wp.blockInputWeightMatrix, lstm_wp.outputGateWeightMatrix, lstm_wp.inputGateRecursionMatrix, lstm_wp.forgetGateRecursionMatrix, lstm_wp.blockInputRecursionMatrix, lstm_wp.outputGateRecursionMatrix, lstm_wp.inputGateBiasVector, lstm_wp.forgetGateBiasVector, lstm_wp.blockInputBiasVector, lstm_wp.outputGateBiasVector, lstm_wp.inputGatePeepholeVector, lstm_wp.forgetGatePeepholeVector, lstm_wp.outputGatePeepholeVector, ]
Get LSTM weight fields. lstm_wp: _NeuralNetwork_pb2.LSTMWeightParams
Get LSTM weight fields. lstm_wp: _NeuralNetwork_pb2.LSTMWeightParams
[ "Get", "LSTM", "weight", "fields", ".", "lstm_wp", ":", "_NeuralNetwork_pb2", ".", "LSTMWeightParams" ]
def _get_lstm_weight_fields(lstm_wp): """ Get LSTM weight fields. lstm_wp: _NeuralNetwork_pb2.LSTMWeightParams """ return [ lstm_wp.inputGateWeightMatrix, lstm_wp.forgetGateWeightMatrix, lstm_wp.blockInputWeightMatrix, lstm_wp.outputGateWeightMatrix, lstm_wp.inputGateRecursionMatrix, lstm_wp.forgetGateRecursionMatrix, lstm_wp.blockInputRecursionMatrix, lstm_wp.outputGateRecursionMatrix, lstm_wp.inputGateBiasVector, lstm_wp.forgetGateBiasVector, lstm_wp.blockInputBiasVector, lstm_wp.outputGateBiasVector, lstm_wp.inputGatePeepholeVector, lstm_wp.forgetGatePeepholeVector, lstm_wp.outputGatePeepholeVector, ]
[ "def", "_get_lstm_weight_fields", "(", "lstm_wp", ")", ":", "return", "[", "lstm_wp", ".", "inputGateWeightMatrix", ",", "lstm_wp", ".", "forgetGateWeightMatrix", ",", "lstm_wp", ".", "blockInputWeightMatrix", ",", "lstm_wp", ".", "outputGateWeightMatrix", ",", "lstm_...
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/coremltools/models/neural_network/builder.py#L146-L167
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/aui/aui_utilities.py
python
FindFocusDescendant
(ancestor)
return focusWin
Find a window with the focus, that is also a descendant of the given window. This is used to determine the window to initially send commands to. :param wx.Window `ancestor`: the window to check for ancestry.
Find a window with the focus, that is also a descendant of the given window. This is used to determine the window to initially send commands to.
[ "Find", "a", "window", "with", "the", "focus", "that", "is", "also", "a", "descendant", "of", "the", "given", "window", ".", "This", "is", "used", "to", "determine", "the", "window", "to", "initially", "send", "commands", "to", "." ]
def FindFocusDescendant(ancestor): """ Find a window with the focus, that is also a descendant of the given window. This is used to determine the window to initially send commands to. :param wx.Window `ancestor`: the window to check for ancestry. """ # Process events starting with the window with the focus, if any. focusWin = wx.Window.FindFocus() win = focusWin # Check if this is a descendant of this frame. # If not, win will be set to NULL. while win: if win == ancestor: break else: win = win.GetParent() if win is None: focusWin = None return focusWin
[ "def", "FindFocusDescendant", "(", "ancestor", ")", ":", "# Process events starting with the window with the focus, if any.", "focusWin", "=", "wx", ".", "Window", ".", "FindFocus", "(", ")", "win", "=", "focusWin", "# Check if this is a descendant of this frame.", "# If not,...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/aui/aui_utilities.py#L349-L372
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pymongo/pool.py
python
Pool.__init__
(self, address, options, handshake=True)
:Parameters: - `address`: a (hostname, port) tuple - `options`: a PoolOptions instance - `handshake`: whether to call ismaster for each new SocketInfo
:Parameters: - `address`: a (hostname, port) tuple - `options`: a PoolOptions instance - `handshake`: whether to call ismaster for each new SocketInfo
[ ":", "Parameters", ":", "-", "address", ":", "a", "(", "hostname", "port", ")", "tuple", "-", "options", ":", "a", "PoolOptions", "instance", "-", "handshake", ":", "whether", "to", "call", "ismaster", "for", "each", "new", "SocketInfo" ]
def __init__(self, address, options, handshake=True): """ :Parameters: - `address`: a (hostname, port) tuple - `options`: a PoolOptions instance - `handshake`: whether to call ismaster for each new SocketInfo """ # Check a socket's health with socket_closed() every once in a while. # Can override for testing: 0 to always check, None to never check. self._check_interval_seconds = 1 # LIFO pool. Sockets are ordered on idle time. Sockets claimed # and returned to pool from the left side. Stale sockets removed # from the right side. self.sockets = collections.deque() self.lock = threading.Lock() self.active_sockets = 0 # Monotonically increasing connection ID required for CMAP Events. self.next_connection_id = 1 self.closed = False # Track whether the sockets in this pool are writeable or not. self.is_writable = None # Keep track of resets, so we notice sockets created before the most # recent reset and close them. self.pool_id = 0 self.pid = os.getpid() self.address = address self.opts = options self.handshake = handshake # Don't publish events in Monitor pools. self.enabled_for_cmap = ( self.handshake and self.opts.event_listeners is not None and self.opts.event_listeners.enabled_for_cmap) if (self.opts.wait_queue_multiple is None or self.opts.max_pool_size is None): max_waiters = None else: max_waiters = ( self.opts.max_pool_size * self.opts.wait_queue_multiple) self._socket_semaphore = thread_util.create_semaphore( self.opts.max_pool_size, max_waiters) self.socket_checker = SocketChecker() if self.enabled_for_cmap: self.opts.event_listeners.publish_pool_created( self.address, self.opts.non_default_options)
[ "def", "__init__", "(", "self", ",", "address", ",", "options", ",", "handshake", "=", "True", ")", ":", "# Check a socket's health with socket_closed() every once in a while.", "# Can override for testing: 0 to always check, None to never check.", "self", ".", "_check_interval_s...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pymongo/pool.py#L946-L993
regel/loudml
0008baef02259a8ae81dd210d3f91a51ffc9ed9f
loudml/storage.py
python
Storage.get_model_hook
(self, model_name, hook_name)
Get model hook
Get model hook
[ "Get", "model", "hook" ]
def get_model_hook(self, model_name, hook_name): """Get model hook"""
[ "def", "get_model_hook", "(", "self", ",", "model_name", ",", "hook_name", ")", ":" ]
https://github.com/regel/loudml/blob/0008baef02259a8ae81dd210d3f91a51ffc9ed9f/loudml/storage.py#L118-L119
NeuralEnsemble/python-neo
34d4db8fb0dc950dbbc6defd7fb75e99ea877286
neo/rawio/baserawio.py
python
BaseRawIO.source_name
(self)
return self._source_name()
Return fancy name of file source
Return fancy name of file source
[ "Return", "fancy", "name", "of", "file", "source" ]
def source_name(self): """Return fancy name of file source""" return self._source_name()
[ "def", "source_name", "(", "self", ")", ":", "return", "self", ".", "_source_name", "(", ")" ]
https://github.com/NeuralEnsemble/python-neo/blob/34d4db8fb0dc950dbbc6defd7fb75e99ea877286/neo/rawio/baserawio.py#L188-L190
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/fps/connection.py
python
FPSConnection.get_recipient_verification_status
(self, action, response, **kw)
return self.get_object(action, kw, response)
Returns the recipient status.
Returns the recipient status.
[ "Returns", "the", "recipient", "status", "." ]
def get_recipient_verification_status(self, action, response, **kw): """ Returns the recipient status. """ return self.get_object(action, kw, response)
[ "def", "get_recipient_verification_status", "(", "self", ",", "action", ",", "response", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "get_object", "(", "action", ",", "kw", ",", "response", ")" ]
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/fps/connection.py#L281-L285
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/gs/key.py
python
Key.set_xml_acl
(self, acl_str, headers=None, generation=None, if_generation=None, if_metageneration=None)
Sets this objects's ACL to an XML string. :type acl_str: string :param acl_str: A string containing the ACL XML. :type headers: dict :param headers: Additional headers to set during the request. :type generation: int :param generation: If specified, sets the ACL for a specific generation of a versioned object. If not specified, the current version is modified. :type if_generation: int :param if_generation: (optional) If set to a generation number, the acl will only be updated if its current generation number is this value. :type if_metageneration: int :param if_metageneration: (optional) If set to a metageneration number, the acl will only be updated if its current metageneration number is this value.
Sets this objects's ACL to an XML string.
[ "Sets", "this", "objects", "s", "ACL", "to", "an", "XML", "string", "." ]
def set_xml_acl(self, acl_str, headers=None, generation=None, if_generation=None, if_metageneration=None): """Sets this objects's ACL to an XML string. :type acl_str: string :param acl_str: A string containing the ACL XML. :type headers: dict :param headers: Additional headers to set during the request. :type generation: int :param generation: If specified, sets the ACL for a specific generation of a versioned object. If not specified, the current version is modified. :type if_generation: int :param if_generation: (optional) If set to a generation number, the acl will only be updated if its current generation number is this value. :type if_metageneration: int :param if_metageneration: (optional) If set to a metageneration number, the acl will only be updated if its current metageneration number is this value. """ if self.bucket is not None: return self.bucket.set_xml_acl(acl_str, self.name, headers=headers, generation=generation, if_generation=if_generation, if_metageneration=if_metageneration)
[ "def", "set_xml_acl", "(", "self", ",", "acl_str", ",", "headers", "=", "None", ",", "generation", "=", "None", ",", "if_generation", "=", "None", ",", "if_metageneration", "=", "None", ")", ":", "if", "self", ".", "bucket", "is", "not", "None", ":", "...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/gs/key.py#L842-L870
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/future/backports/misc.py
python
ChainMap.popitem
(self)
Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.
Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.
[ "Remove", "and", "return", "an", "item", "pair", "from", "maps", "[", "0", "]", ".", "Raise", "KeyError", "is", "maps", "[", "0", "]", "is", "empty", "." ]
def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except KeyError: raise KeyError('No keys found in the first mapping.')
[ "def", "popitem", "(", "self", ")", ":", "try", ":", "return", "self", ".", "maps", "[", "0", "]", ".", "popitem", "(", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'No keys found in the first mapping.'", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/misc.py#L826-L831
MaybeShewill-CV/lanenet-lane-detection
94be8d9a66c7bbda5ad99b10492bc406c8aee45f
lanenet_model/lanenet_discriminative_loss.py
python
discriminative_loss_single
( prediction, correct_label, feature_dim, label_shape, delta_v, delta_d, param_var, param_dist, param_reg)
return loss, l_var, l_dist, l_reg
discriminative loss :param prediction: inference of network :param correct_label: instance label :param feature_dim: feature dimension of prediction :param label_shape: shape of label :param delta_v: cut off variance distance :param delta_d: cut off cluster distance :param param_var: weight for intra cluster variance :param param_dist: weight for inter cluster distances :param param_reg: weight regularization
discriminative loss :param prediction: inference of network :param correct_label: instance label :param feature_dim: feature dimension of prediction :param label_shape: shape of label :param delta_v: cut off variance distance :param delta_d: cut off cluster distance :param param_var: weight for intra cluster variance :param param_dist: weight for inter cluster distances :param param_reg: weight regularization
[ "discriminative", "loss", ":", "param", "prediction", ":", "inference", "of", "network", ":", "param", "correct_label", ":", "instance", "label", ":", "param", "feature_dim", ":", "feature", "dimension", "of", "prediction", ":", "param", "label_shape", ":", "sha...
def discriminative_loss_single( prediction, correct_label, feature_dim, label_shape, delta_v, delta_d, param_var, param_dist, param_reg): """ discriminative loss :param prediction: inference of network :param correct_label: instance label :param feature_dim: feature dimension of prediction :param label_shape: shape of label :param delta_v: cut off variance distance :param delta_d: cut off cluster distance :param param_var: weight for intra cluster variance :param param_dist: weight for inter cluster distances :param param_reg: weight regularization """ correct_label = tf.reshape( correct_label, [label_shape[1] * label_shape[0]] ) reshaped_pred = tf.reshape( prediction, [label_shape[1] * label_shape[0], feature_dim] ) # calculate instance nums unique_labels, unique_id, counts = tf.unique_with_counts(correct_label) counts = tf.cast(counts, tf.float32) num_instances = tf.size(unique_labels) # calculate instance pixel embedding mean vec segmented_sum = tf.unsorted_segment_sum( reshaped_pred, unique_id, num_instances) mu = tf.div(segmented_sum, tf.reshape(counts, (-1, 1))) mu_expand = tf.gather(mu, unique_id) distance = tf.norm(tf.subtract(mu_expand, reshaped_pred), axis=1, ord=1) distance = tf.subtract(distance, delta_v) distance = tf.clip_by_value(distance, 0., distance) distance = tf.square(distance) l_var = tf.unsorted_segment_sum(distance, unique_id, num_instances) l_var = tf.div(l_var, counts) l_var = tf.reduce_sum(l_var) l_var = tf.divide(l_var, tf.cast(num_instances, tf.float32)) mu_interleaved_rep = tf.tile(mu, [num_instances, 1]) mu_band_rep = tf.tile(mu, [1, num_instances]) mu_band_rep = tf.reshape( mu_band_rep, (num_instances * num_instances, feature_dim)) mu_diff = tf.subtract(mu_band_rep, mu_interleaved_rep) intermediate_tensor = tf.reduce_sum(tf.abs(mu_diff), axis=1) zero_vector = tf.zeros(1, dtype=tf.float32) bool_mask = tf.not_equal(intermediate_tensor, zero_vector) mu_diff_bool = tf.boolean_mask(mu_diff, bool_mask) mu_norm = tf.norm(mu_diff_bool, axis=1, ord=1) mu_norm = tf.subtract(2. * delta_d, mu_norm) mu_norm = tf.clip_by_value(mu_norm, 0., mu_norm) mu_norm = tf.square(mu_norm) l_dist = tf.reduce_mean(mu_norm) l_reg = tf.reduce_mean(tf.norm(mu, axis=1, ord=1)) param_scale = 1. l_var = param_var * l_var l_dist = param_dist * l_dist l_reg = param_reg * l_reg loss = param_scale * (l_var + l_dist + l_reg) return loss, l_var, l_dist, l_reg
[ "def", "discriminative_loss_single", "(", "prediction", ",", "correct_label", ",", "feature_dim", ",", "label_shape", ",", "delta_v", ",", "delta_d", ",", "param_var", ",", "param_dist", ",", "param_reg", ")", ":", "correct_label", "=", "tf", ".", "reshape", "("...
https://github.com/MaybeShewill-CV/lanenet-lane-detection/blob/94be8d9a66c7bbda5ad99b10492bc406c8aee45f/lanenet_model/lanenet_discriminative_loss.py#L14-L95
hgrecco/pint
befdffb9d767fb354fc756660a33268c0f8d48e1
pint/numpy_func.py
python
convert_arg
(arg, pre_calc_units)
return arg
Convert quantities and sequences of quantities to pre_calc_units and strip units. Helper function for convert_to_consistent_units. pre_calc_units must be given as a pint Unit or None.
Convert quantities and sequences of quantities to pre_calc_units and strip units.
[ "Convert", "quantities", "and", "sequences", "of", "quantities", "to", "pre_calc_units", "and", "strip", "units", "." ]
def convert_arg(arg, pre_calc_units): """Convert quantities and sequences of quantities to pre_calc_units and strip units. Helper function for convert_to_consistent_units. pre_calc_units must be given as a pint Unit or None. """ if pre_calc_units is not None: if _is_quantity(arg): return arg.m_as(pre_calc_units) elif _is_sequence_with_quantity_elements(arg): return [convert_arg(item, pre_calc_units) for item in arg] elif arg is not None: if pre_calc_units.dimensionless: return pre_calc_units._REGISTRY.Quantity(arg).m_as(pre_calc_units) elif not _is_quantity(arg) and zero_or_nan(arg, True): return arg else: raise DimensionalityError("dimensionless", pre_calc_units) elif _is_quantity(arg): return arg.m elif _is_sequence_with_quantity_elements(arg): return [convert_arg(item, pre_calc_units) for item in arg] return arg
[ "def", "convert_arg", "(", "arg", ",", "pre_calc_units", ")", ":", "if", "pre_calc_units", "is", "not", "None", ":", "if", "_is_quantity", "(", "arg", ")", ":", "return", "arg", ".", "m_as", "(", "pre_calc_units", ")", "elif", "_is_sequence_with_quantity_eleme...
https://github.com/hgrecco/pint/blob/befdffb9d767fb354fc756660a33268c0f8d48e1/pint/numpy_func.py#L72-L94
IBM/lale
b4d6829c143a4735b06083a0e6c70d2cca244162
lale/lib/autoai_libs/cat_encoder.py
python
_CatEncoderImpl.__init__
( self, encoding, categories, dtype, handle_unknown, sklearn_version_family=None, activate_flag=True, encode_unknown_with="auto", )
[]
def __init__( self, encoding, categories, dtype, handle_unknown, sklearn_version_family=None, activate_flag=True, encode_unknown_with="auto", ): self._hyperparams = { "encoding": encoding, "categories": categories, "dtype": dtype, "handle_unknown": handle_unknown, "sklearn_version_family": sklearn_version_family, "activate_flag": activate_flag, } self.encode_unknown_with = encode_unknown_with self._wrapped_model = autoai_libs.transformers.exportable.CatEncoder( **self._hyperparams )
[ "def", "__init__", "(", "self", ",", "encoding", ",", "categories", ",", "dtype", ",", "handle_unknown", ",", "sklearn_version_family", "=", "None", ",", "activate_flag", "=", "True", ",", "encode_unknown_with", "=", "\"auto\"", ",", ")", ":", "self", ".", "...
https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/lib/autoai_libs/cat_encoder.py#L23-L44
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/heapq.py
python
heapreplace
(heap, item)
return returnitem
Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement: if item > heap[0]: item = heapreplace(heap, item)
Pop and return the current smallest value, and add the new item.
[ "Pop", "and", "return", "the", "current", "smallest", "value", "and", "add", "the", "new", "item", "." ]
def heapreplace(heap, item): """Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement: if item > heap[0]: item = heapreplace(heap, item) """ returnitem = heap[0] # raises appropriate IndexError if heap is empty heap[0] = item _siftup(heap, 0) return returnitem
[ "def", "heapreplace", "(", "heap", ",", "item", ")", ":", "returnitem", "=", "heap", "[", "0", "]", "# raises appropriate IndexError if heap is empty", "heap", "[", "0", "]", "=", "item", "_siftup", "(", "heap", ",", "0", ")", "return", "returnitem" ]
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/heapq.py#L148-L162
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/cosigner_pool/qt.py
python
Listener.__init__
(self, parent)
[]
def __init__(self, parent): util.DaemonThread.__init__(self) self.daemon = True self.parent = parent self.received = set() self.keyhashes = []
[ "def", "__init__", "(", "self", ",", "parent", ")", ":", "util", ".", "DaemonThread", ".", "__init__", "(", "self", ")", "self", ".", "daemon", "=", "True", "self", ".", "parent", "=", "parent", "self", ".", "received", "=", "set", "(", ")", "self", ...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/cosigner_pool/qt.py#L59-L64
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/tts/modules/melgan_modules.py
python
MelGANMultiScaleDiscriminator.reset_parameters
(self)
Reset parameters. This initialization follows official implementation manner. https://github.com/descriptinc/melgan-neurips/blob/master/mel2wav/modules.py
Reset parameters.
[ "Reset", "parameters", "." ]
def reset_parameters(self): """Reset parameters. This initialization follows official implementation manner. https://github.com/descriptinc/melgan-neurips/blob/master/mel2wav/modules.py """ def _reset_parameters(module): if isinstance(module, torch.nn.Conv1d) or isinstance(module, torch.nn.ConvTranspose1d): module.weight.data.normal_(0.0, 0.02) logging.debug(f"Reset parameters in {module}.") self.apply(_reset_parameters)
[ "def", "reset_parameters", "(", "self", ")", ":", "def", "_reset_parameters", "(", "module", ")", ":", "if", "isinstance", "(", "module", ",", "torch", ".", "nn", ".", "Conv1d", ")", "or", "isinstance", "(", "module", ",", "torch", ".", "nn", ".", "Con...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/tts/modules/melgan_modules.py#L495-L508
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/asyncio/futures.py
python
Future.result
(self)
return self._result
Return the result this future represents. If the future has been cancelled, raises CancelledError. If the future's result isn't yet available, raises InvalidStateError. If the future is done and has an exception set, this exception is raised.
Return the result this future represents.
[ "Return", "the", "result", "this", "future", "represents", "." ]
def result(self): """Return the result this future represents. If the future has been cancelled, raises CancelledError. If the future's result isn't yet available, raises InvalidStateError. If the future is done and has an exception set, this exception is raised. """ if self._state == _CANCELLED: raise CancelledError if self._state != _FINISHED: raise InvalidStateError('Result is not ready.') self._log_traceback = False if self._tb_logger is not None: self._tb_logger.clear() self._tb_logger = None if self._exception is not None: raise self._exception return self._result
[ "def", "result", "(", "self", ")", ":", "if", "self", ".", "_state", "==", "_CANCELLED", ":", "raise", "CancelledError", "if", "self", ".", "_state", "!=", "_FINISHED", ":", "raise", "InvalidStateError", "(", "'Result is not ready.'", ")", "self", ".", "_log...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/asyncio/futures.py#L258-L275