repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
hubo1016/vlcp | vlcp/server/module.py | ModuleAPIHandler.unregisterAPI | def unregisterAPI(self, name):
"""
Remove an API from this handler
"""
if name.startswith('public/'):
target = 'public'
name = name[len('public/'):]
else:
target = self.servicename
name = name
removes = [m for m in self.handler.handlers.keys() if m.target == target and m.name == name]
for m in removes:
self.handler.unregisterHandler(m) | python | def unregisterAPI(self, name):
"""
Remove an API from this handler
"""
if name.startswith('public/'):
target = 'public'
name = name[len('public/'):]
else:
target = self.servicename
name = name
removes = [m for m in self.handler.handlers.keys() if m.target == target and m.name == name]
for m in removes:
self.handler.unregisterHandler(m) | [
"def",
"unregisterAPI",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'public/'",
")",
":",
"target",
"=",
"'public'",
"name",
"=",
"name",
"[",
"len",
"(",
"'public/'",
")",
":",
"]",
"else",
":",
"target",
"=",
"self",
".",
"servicename",
"name",
"=",
"name",
"removes",
"=",
"[",
"m",
"for",
"m",
"in",
"self",
".",
"handler",
".",
"handlers",
".",
"keys",
"(",
")",
"if",
"m",
".",
"target",
"==",
"target",
"and",
"m",
".",
"name",
"==",
"name",
"]",
"for",
"m",
"in",
"removes",
":",
"self",
".",
"handler",
".",
"unregisterHandler",
"(",
"m",
")"
] | Remove an API from this handler | [
"Remove",
"an",
"API",
"from",
"this",
"handler"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L229-L241 |
hubo1016/vlcp | vlcp/server/module.py | ModuleAPIHandler.discover | def discover(self, details = False):
'Discover API definitions. Set details=true to show details'
if details and not (isinstance(details, str) and details.lower() == 'false'):
return copy.deepcopy(self.discoverinfo)
else:
return dict((k,v.get('description', '')) for k,v in self.discoverinfo.items()) | python | def discover(self, details = False):
'Discover API definitions. Set details=true to show details'
if details and not (isinstance(details, str) and details.lower() == 'false'):
return copy.deepcopy(self.discoverinfo)
else:
return dict((k,v.get('description', '')) for k,v in self.discoverinfo.items()) | [
"def",
"discover",
"(",
"self",
",",
"details",
"=",
"False",
")",
":",
"if",
"details",
"and",
"not",
"(",
"isinstance",
"(",
"details",
",",
"str",
")",
"and",
"details",
".",
"lower",
"(",
")",
"==",
"'false'",
")",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"discoverinfo",
")",
"else",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"v",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"discoverinfo",
".",
"items",
"(",
")",
")"
] | Discover API definitions. Set details=true to show details | [
"Discover",
"API",
"definitions",
".",
"Set",
"details",
"=",
"true",
"to",
"show",
"details"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L242-L247 |
hubo1016/vlcp | vlcp/server/module.py | ModuleLoader.loadmodule | async def loadmodule(self, module):
'''
Load a module class
'''
self._logger.debug('Try to load module %r', module)
if hasattr(module, '_instance'):
self._logger.debug('Module is already initialized, module state is: %r', module._instance.state)
if module._instance.state == ModuleLoadStateChanged.UNLOADING or module._instance.state == ModuleLoadStateChanged.UNLOADED:
# Wait for unload
um = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.UNLOADED)
await um
elif module._instance.state == ModuleLoadStateChanged.SUCCEEDED:
pass
elif module._instance.state == ModuleLoadStateChanged.FAILED:
raise ModuleLoadException('Cannot load module %r before unloading the failed instance' % (module,))
elif module._instance.state == ModuleLoadStateChanged.NOTLOADED or module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
# Wait for succeeded or failed
sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
_, m = await M_(sm, fm)
if m is sm:
pass
else:
raise ModuleLoadException('Module load failed for %r' % (module,))
if not hasattr(module, '_instance'):
self._logger.info('Loading module %r', module)
inst = module(self.server)
# Avoid duplicated loading
module._instance = inst
# When reloading, some of the dependencies are broken, repair them
if hasattr(module, 'referencedBy'):
inst.dependedBy = set([m for m in module.referencedBy if hasattr(m, '_instance') and m._instance.state != ModuleLoadStateChanged.UNLOADED])
# Load Module
for d in module.depends:
if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.FAILED:
raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, d))
try:
for d in module.depends:
if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.SUCCEEDED:
d._instance.dependedBy.add(module)
preloads = [d for d in module.depends if not hasattr(d, '_instance') or \
d._instance.state != ModuleLoadStateChanged.SUCCEEDED]
for d in preloads:
self.subroutine(self.loadmodule(d), False)
sms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.SUCCEEDED) for d in preloads]
fms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.FAILED) for d in preloads]
def _callback(event, matcher):
raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, event.module))
await self.with_callback(self.wait_for_all(*sms), _callback, *fms)
except:
for d in module.depends:
if hasattr(d, '_instance') and module in d._instance.dependedBy:
self._removeDepend(module, d)
self._logger.warning('Loading module %r stopped', module, exc_info=True)
# Not loaded, send a message to notify that parents can not
async def _msg():
await self.wait_for_send(ModuleLoadStateChanged(module, ModuleLoadStateChanged.UNLOADED, inst))
self.subroutine(_msg(), False)
del module._instance
raise
for d in preloads:
d._instance.dependedBy.add(module)
self.activeModules[inst.getServiceName()] = module
await module._instance.changestate(ModuleLoadStateChanged.LOADING, self)
await module._instance.load(self)
if module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
_, m = await M_(sm, fm)
if m is sm:
pass
else:
raise ModuleLoadException('Module load failed for %r' % (module,))
self._logger.info('Loading module %r completed, module state is %r', module, module._instance.state)
if module._instance.state == ModuleLoadStateChanged.FAILED:
raise ModuleLoadException('Module load failed for %r' % (module,)) | python | async def loadmodule(self, module):
'''
Load a module class
'''
self._logger.debug('Try to load module %r', module)
if hasattr(module, '_instance'):
self._logger.debug('Module is already initialized, module state is: %r', module._instance.state)
if module._instance.state == ModuleLoadStateChanged.UNLOADING or module._instance.state == ModuleLoadStateChanged.UNLOADED:
# Wait for unload
um = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.UNLOADED)
await um
elif module._instance.state == ModuleLoadStateChanged.SUCCEEDED:
pass
elif module._instance.state == ModuleLoadStateChanged.FAILED:
raise ModuleLoadException('Cannot load module %r before unloading the failed instance' % (module,))
elif module._instance.state == ModuleLoadStateChanged.NOTLOADED or module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
# Wait for succeeded or failed
sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
_, m = await M_(sm, fm)
if m is sm:
pass
else:
raise ModuleLoadException('Module load failed for %r' % (module,))
if not hasattr(module, '_instance'):
self._logger.info('Loading module %r', module)
inst = module(self.server)
# Avoid duplicated loading
module._instance = inst
# When reloading, some of the dependencies are broken, repair them
if hasattr(module, 'referencedBy'):
inst.dependedBy = set([m for m in module.referencedBy if hasattr(m, '_instance') and m._instance.state != ModuleLoadStateChanged.UNLOADED])
# Load Module
for d in module.depends:
if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.FAILED:
raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, d))
try:
for d in module.depends:
if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.SUCCEEDED:
d._instance.dependedBy.add(module)
preloads = [d for d in module.depends if not hasattr(d, '_instance') or \
d._instance.state != ModuleLoadStateChanged.SUCCEEDED]
for d in preloads:
self.subroutine(self.loadmodule(d), False)
sms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.SUCCEEDED) for d in preloads]
fms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.FAILED) for d in preloads]
def _callback(event, matcher):
raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, event.module))
await self.with_callback(self.wait_for_all(*sms), _callback, *fms)
except:
for d in module.depends:
if hasattr(d, '_instance') and module in d._instance.dependedBy:
self._removeDepend(module, d)
self._logger.warning('Loading module %r stopped', module, exc_info=True)
# Not loaded, send a message to notify that parents can not
async def _msg():
await self.wait_for_send(ModuleLoadStateChanged(module, ModuleLoadStateChanged.UNLOADED, inst))
self.subroutine(_msg(), False)
del module._instance
raise
for d in preloads:
d._instance.dependedBy.add(module)
self.activeModules[inst.getServiceName()] = module
await module._instance.changestate(ModuleLoadStateChanged.LOADING, self)
await module._instance.load(self)
if module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
_, m = await M_(sm, fm)
if m is sm:
pass
else:
raise ModuleLoadException('Module load failed for %r' % (module,))
self._logger.info('Loading module %r completed, module state is %r', module, module._instance.state)
if module._instance.state == ModuleLoadStateChanged.FAILED:
raise ModuleLoadException('Module load failed for %r' % (module,)) | [
"async",
"def",
"loadmodule",
"(",
"self",
",",
"module",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Try to load module %r'",
",",
"module",
")",
"if",
"hasattr",
"(",
"module",
",",
"'_instance'",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Module is already initialized, module state is: %r'",
",",
"module",
".",
"_instance",
".",
"state",
")",
"if",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"UNLOADING",
"or",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"UNLOADED",
":",
"# Wait for unload",
"um",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"UNLOADED",
")",
"await",
"um",
"elif",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
":",
"pass",
"elif",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"FAILED",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot load module %r before unloading the failed instance'",
"%",
"(",
"module",
",",
")",
")",
"elif",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"NOTLOADED",
"or",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"LOADED",
"or",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"LOADING",
":",
"# Wait for succeeded or failed",
"sm",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
")",
"fm",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"FAILED",
")",
"_",
",",
"m",
"=",
"await",
"M_",
"(",
"sm",
",",
"fm",
")",
"if",
"m",
"is",
"sm",
":",
"pass",
"else",
":",
"raise",
"ModuleLoadException",
"(",
"'Module load failed for %r'",
"%",
"(",
"module",
",",
")",
")",
"if",
"not",
"hasattr",
"(",
"module",
",",
"'_instance'",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Loading module %r'",
",",
"module",
")",
"inst",
"=",
"module",
"(",
"self",
".",
"server",
")",
"# Avoid duplicated loading",
"module",
".",
"_instance",
"=",
"inst",
"# When reloading, some of the dependencies are broken, repair them",
"if",
"hasattr",
"(",
"module",
",",
"'referencedBy'",
")",
":",
"inst",
".",
"dependedBy",
"=",
"set",
"(",
"[",
"m",
"for",
"m",
"in",
"module",
".",
"referencedBy",
"if",
"hasattr",
"(",
"m",
",",
"'_instance'",
")",
"and",
"m",
".",
"_instance",
".",
"state",
"!=",
"ModuleLoadStateChanged",
".",
"UNLOADED",
"]",
")",
"# Load Module",
"for",
"d",
"in",
"module",
".",
"depends",
":",
"if",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
"and",
"d",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"FAILED",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot load module %r, it depends on %r, which is in failed state.'",
"%",
"(",
"module",
",",
"d",
")",
")",
"try",
":",
"for",
"d",
"in",
"module",
".",
"depends",
":",
"if",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
"and",
"d",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
":",
"d",
".",
"_instance",
".",
"dependedBy",
".",
"add",
"(",
"module",
")",
"preloads",
"=",
"[",
"d",
"for",
"d",
"in",
"module",
".",
"depends",
"if",
"not",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
"or",
"d",
".",
"_instance",
".",
"state",
"!=",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
"]",
"for",
"d",
"in",
"preloads",
":",
"self",
".",
"subroutine",
"(",
"self",
".",
"loadmodule",
"(",
"d",
")",
",",
"False",
")",
"sms",
"=",
"[",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"d",
",",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
")",
"for",
"d",
"in",
"preloads",
"]",
"fms",
"=",
"[",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"d",
",",
"ModuleLoadStateChanged",
".",
"FAILED",
")",
"for",
"d",
"in",
"preloads",
"]",
"def",
"_callback",
"(",
"event",
",",
"matcher",
")",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot load module %r, it depends on %r, which is in failed state.'",
"%",
"(",
"module",
",",
"event",
".",
"module",
")",
")",
"await",
"self",
".",
"with_callback",
"(",
"self",
".",
"wait_for_all",
"(",
"*",
"sms",
")",
",",
"_callback",
",",
"*",
"fms",
")",
"except",
":",
"for",
"d",
"in",
"module",
".",
"depends",
":",
"if",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
"and",
"module",
"in",
"d",
".",
"_instance",
".",
"dependedBy",
":",
"self",
".",
"_removeDepend",
"(",
"module",
",",
"d",
")",
"self",
".",
"_logger",
".",
"warning",
"(",
"'Loading module %r stopped'",
",",
"module",
",",
"exc_info",
"=",
"True",
")",
"# Not loaded, send a message to notify that parents can not ",
"async",
"def",
"_msg",
"(",
")",
":",
"await",
"self",
".",
"wait_for_send",
"(",
"ModuleLoadStateChanged",
"(",
"module",
",",
"ModuleLoadStateChanged",
".",
"UNLOADED",
",",
"inst",
")",
")",
"self",
".",
"subroutine",
"(",
"_msg",
"(",
")",
",",
"False",
")",
"del",
"module",
".",
"_instance",
"raise",
"for",
"d",
"in",
"preloads",
":",
"d",
".",
"_instance",
".",
"dependedBy",
".",
"add",
"(",
"module",
")",
"self",
".",
"activeModules",
"[",
"inst",
".",
"getServiceName",
"(",
")",
"]",
"=",
"module",
"await",
"module",
".",
"_instance",
".",
"changestate",
"(",
"ModuleLoadStateChanged",
".",
"LOADING",
",",
"self",
")",
"await",
"module",
".",
"_instance",
".",
"load",
"(",
"self",
")",
"if",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"LOADED",
"or",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"LOADING",
":",
"sm",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
")",
"fm",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"FAILED",
")",
"_",
",",
"m",
"=",
"await",
"M_",
"(",
"sm",
",",
"fm",
")",
"if",
"m",
"is",
"sm",
":",
"pass",
"else",
":",
"raise",
"ModuleLoadException",
"(",
"'Module load failed for %r'",
"%",
"(",
"module",
",",
")",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Loading module %r completed, module state is %r'",
",",
"module",
",",
"module",
".",
"_instance",
".",
"state",
")",
"if",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"FAILED",
":",
"raise",
"ModuleLoadException",
"(",
"'Module load failed for %r'",
"%",
"(",
"module",
",",
")",
")"
] | Load a module class | [
"Load",
"a",
"module",
"class"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L502-L577 |
hubo1016/vlcp | vlcp/server/module.py | ModuleLoader.unloadmodule | async def unloadmodule(self, module, ignoreDependencies = False):
'''
Unload a module class
'''
self._logger.debug('Try to unload module %r', module)
if hasattr(module, '_instance'):
self._logger.debug('Module %r is loaded, module state is %r', module, module._instance.state)
inst = module._instance
if inst.state == ModuleLoadStateChanged.LOADING or inst.state == ModuleLoadStateChanged.LOADED:
# Wait for loading
# Wait for succeeded or failed
sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
await M_(sm, fm)
elif inst.state == ModuleLoadStateChanged.UNLOADING or inst.state == ModuleLoadStateChanged.UNLOADED:
um = ModuleLoadStateChanged.createMatcher(module, ModuleLoadStateChanged.UNLOADED)
await um
if hasattr(module, '_instance') and (module._instance.state == ModuleLoadStateChanged.SUCCEEDED or
module._instance.state == ModuleLoadStateChanged.FAILED):
self._logger.info('Unloading module %r', module)
inst = module._instance
# Change state to unloading to prevent more dependencies
await inst.changestate(ModuleLoadStateChanged.UNLOADING, self)
if not ignoreDependencies:
deps = [d for d in inst.dependedBy if hasattr(d, '_instance') and d._instance.state != ModuleLoadStateChanged.UNLOADED]
ums = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.UNLOADED) for d in deps]
for d in deps:
self.subroutine(self.unloadmodule(d), False)
await self.wait_for_all(*ums)
await inst.unload(self)
del self.activeModules[inst.getServiceName()]
self._logger.info('Module %r is unloaded', module)
if not ignoreDependencies:
for d in module.depends:
if hasattr(d, '_instance') and module in d._instance.dependedBy:
self._removeDepend(module, d) | python | async def unloadmodule(self, module, ignoreDependencies = False):
'''
Unload a module class
'''
self._logger.debug('Try to unload module %r', module)
if hasattr(module, '_instance'):
self._logger.debug('Module %r is loaded, module state is %r', module, module._instance.state)
inst = module._instance
if inst.state == ModuleLoadStateChanged.LOADING or inst.state == ModuleLoadStateChanged.LOADED:
# Wait for loading
# Wait for succeeded or failed
sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
await M_(sm, fm)
elif inst.state == ModuleLoadStateChanged.UNLOADING or inst.state == ModuleLoadStateChanged.UNLOADED:
um = ModuleLoadStateChanged.createMatcher(module, ModuleLoadStateChanged.UNLOADED)
await um
if hasattr(module, '_instance') and (module._instance.state == ModuleLoadStateChanged.SUCCEEDED or
module._instance.state == ModuleLoadStateChanged.FAILED):
self._logger.info('Unloading module %r', module)
inst = module._instance
# Change state to unloading to prevent more dependencies
await inst.changestate(ModuleLoadStateChanged.UNLOADING, self)
if not ignoreDependencies:
deps = [d for d in inst.dependedBy if hasattr(d, '_instance') and d._instance.state != ModuleLoadStateChanged.UNLOADED]
ums = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.UNLOADED) for d in deps]
for d in deps:
self.subroutine(self.unloadmodule(d), False)
await self.wait_for_all(*ums)
await inst.unload(self)
del self.activeModules[inst.getServiceName()]
self._logger.info('Module %r is unloaded', module)
if not ignoreDependencies:
for d in module.depends:
if hasattr(d, '_instance') and module in d._instance.dependedBy:
self._removeDepend(module, d) | [
"async",
"def",
"unloadmodule",
"(",
"self",
",",
"module",
",",
"ignoreDependencies",
"=",
"False",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Try to unload module %r'",
",",
"module",
")",
"if",
"hasattr",
"(",
"module",
",",
"'_instance'",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Module %r is loaded, module state is %r'",
",",
"module",
",",
"module",
".",
"_instance",
".",
"state",
")",
"inst",
"=",
"module",
".",
"_instance",
"if",
"inst",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"LOADING",
"or",
"inst",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"LOADED",
":",
"# Wait for loading",
"# Wait for succeeded or failed",
"sm",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
")",
"fm",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
".",
"_instance",
".",
"target",
",",
"ModuleLoadStateChanged",
".",
"FAILED",
")",
"await",
"M_",
"(",
"sm",
",",
"fm",
")",
"elif",
"inst",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"UNLOADING",
"or",
"inst",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"UNLOADED",
":",
"um",
"=",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"module",
",",
"ModuleLoadStateChanged",
".",
"UNLOADED",
")",
"await",
"um",
"if",
"hasattr",
"(",
"module",
",",
"'_instance'",
")",
"and",
"(",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"SUCCEEDED",
"or",
"module",
".",
"_instance",
".",
"state",
"==",
"ModuleLoadStateChanged",
".",
"FAILED",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Unloading module %r'",
",",
"module",
")",
"inst",
"=",
"module",
".",
"_instance",
"# Change state to unloading to prevent more dependencies",
"await",
"inst",
".",
"changestate",
"(",
"ModuleLoadStateChanged",
".",
"UNLOADING",
",",
"self",
")",
"if",
"not",
"ignoreDependencies",
":",
"deps",
"=",
"[",
"d",
"for",
"d",
"in",
"inst",
".",
"dependedBy",
"if",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
"and",
"d",
".",
"_instance",
".",
"state",
"!=",
"ModuleLoadStateChanged",
".",
"UNLOADED",
"]",
"ums",
"=",
"[",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"d",
",",
"ModuleLoadStateChanged",
".",
"UNLOADED",
")",
"for",
"d",
"in",
"deps",
"]",
"for",
"d",
"in",
"deps",
":",
"self",
".",
"subroutine",
"(",
"self",
".",
"unloadmodule",
"(",
"d",
")",
",",
"False",
")",
"await",
"self",
".",
"wait_for_all",
"(",
"*",
"ums",
")",
"await",
"inst",
".",
"unload",
"(",
"self",
")",
"del",
"self",
".",
"activeModules",
"[",
"inst",
".",
"getServiceName",
"(",
")",
"]",
"self",
".",
"_logger",
".",
"info",
"(",
"'Module %r is unloaded'",
",",
"module",
")",
"if",
"not",
"ignoreDependencies",
":",
"for",
"d",
"in",
"module",
".",
"depends",
":",
"if",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
"and",
"module",
"in",
"d",
".",
"_instance",
".",
"dependedBy",
":",
"self",
".",
"_removeDepend",
"(",
"module",
",",
"d",
")"
] | Unload a module class | [
"Unload",
"a",
"module",
"class"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L578-L613 |
hubo1016/vlcp | vlcp/server/module.py | ModuleLoader.load_by_path | async def load_by_path(self, path):
"""
Load a module by full path. If there are dependencies, they are also loaded.
"""
try:
p, module = findModule(path, True)
except KeyError as exc:
raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + str(exc) + 'is not defined in the package')
except Exception as exc:
raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + str(exc))
if module is None:
raise ModuleLoadException('Cannot find module: ' + repr(path))
return await self.loadmodule(module) | python | async def load_by_path(self, path):
"""
Load a module by full path. If there are dependencies, they are also loaded.
"""
try:
p, module = findModule(path, True)
except KeyError as exc:
raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + str(exc) + 'is not defined in the package')
except Exception as exc:
raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + str(exc))
if module is None:
raise ModuleLoadException('Cannot find module: ' + repr(path))
return await self.loadmodule(module) | [
"async",
"def",
"load_by_path",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"p",
",",
"module",
"=",
"findModule",
"(",
"path",
",",
"True",
")",
"except",
"KeyError",
"as",
"exc",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot load module '",
"+",
"repr",
"(",
"path",
")",
"+",
"': '",
"+",
"str",
"(",
"exc",
")",
"+",
"'is not defined in the package'",
")",
"except",
"Exception",
"as",
"exc",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot load module '",
"+",
"repr",
"(",
"path",
")",
"+",
"': '",
"+",
"str",
"(",
"exc",
")",
")",
"if",
"module",
"is",
"None",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot find module: '",
"+",
"repr",
"(",
"path",
")",
")",
"return",
"await",
"self",
".",
"loadmodule",
"(",
"module",
")"
] | Load a module by full path. If there are dependencies, they are also loaded. | [
"Load",
"a",
"module",
"by",
"full",
"path",
".",
"If",
"there",
"are",
"dependencies",
"they",
"are",
"also",
"loaded",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L614-L626 |
hubo1016/vlcp | vlcp/server/module.py | ModuleLoader.unload_by_path | async def unload_by_path(self, path):
"""
Unload a module by full path. Dependencies are automatically unloaded if they are marked to be
services.
"""
p, module = findModule(path, False)
if module is None:
raise ModuleLoadException('Cannot find module: ' + repr(path))
return await self.unloadmodule(module) | python | async def unload_by_path(self, path):
"""
Unload a module by full path. Dependencies are automatically unloaded if they are marked to be
services.
"""
p, module = findModule(path, False)
if module is None:
raise ModuleLoadException('Cannot find module: ' + repr(path))
return await self.unloadmodule(module) | [
"async",
"def",
"unload_by_path",
"(",
"self",
",",
"path",
")",
":",
"p",
",",
"module",
"=",
"findModule",
"(",
"path",
",",
"False",
")",
"if",
"module",
"is",
"None",
":",
"raise",
"ModuleLoadException",
"(",
"'Cannot find module: '",
"+",
"repr",
"(",
"path",
")",
")",
"return",
"await",
"self",
".",
"unloadmodule",
"(",
"module",
")"
] | Unload a module by full path. Dependencies are automatically unloaded if they are marked to be
services. | [
"Unload",
"a",
"module",
"by",
"full",
"path",
".",
"Dependencies",
"are",
"automatically",
"unloaded",
"if",
"they",
"are",
"marked",
"to",
"be",
"services",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L630-L638 |
hubo1016/vlcp | vlcp/server/module.py | ModuleLoader.reload_modules | async def reload_modules(self, pathlist):
"""
Reload modules with a full path in the pathlist
"""
loadedModules = []
failures = []
for path in pathlist:
p, module = findModule(path, False)
if module is not None and hasattr(module, '_instance') and module._instance.state != ModuleLoadStateChanged.UNLOADED:
loadedModules.append(module)
# Unload all modules
ums = [ModuleLoadStateChanged.createMatcher(m, ModuleLoadStateChanged.UNLOADED) for m in loadedModules]
for m in loadedModules:
# Only unload the module itself, not its dependencies, since we will restart the module soon enough
self.subroutine(self.unloadmodule(m, True), False)
await self.wait_for_all(*ums)
# Group modules by package
grouped = {}
for path in pathlist:
dotpos = path.rfind('.')
if dotpos == -1:
raise ModuleLoadException('Must specify module with full path, including package name')
package = path[:dotpos]
classname = path[dotpos + 1:]
mlist = grouped.setdefault(package, [])
p, module = findModule(path, False)
mlist.append((classname, module))
for package, mlist in grouped.items():
# Reload each package only once
try:
p = sys.modules[package]
# Remove cache to ensure a clean import from source file
removeCache(p)
p = reload(p)
except KeyError:
try:
p = __import__(package, fromlist=[m[0] for m in mlist])
except Exception:
self._logger.warning('Failed to import a package: %r, resume others', package, exc_info = True)
failures.append('Failed to import: ' + package)
continue
except Exception:
self._logger.warning('Failed to import a package: %r, resume others', package, exc_info = True)
failures.append('Failed to import: ' + package)
continue
for cn, module in mlist:
try:
module2 = getattr(p, cn)
except AttributeError:
self._logger.warning('Cannot find module %r in package %r, resume others', package, cn)
failures.append('Failed to import: ' + package + '.' + cn)
continue
if module is not None and module is not module2:
# Update the references
try:
lpos = loadedModules.index(module)
loaded = True
except Exception:
loaded = False
for d in module.depends:
# The new reference is automatically added on import, only remove the old reference
d.referencedBy.remove(module)
if loaded and hasattr(d, '_instance'):
try:
d._instance.dependedBy.remove(module)
d._instance.dependedBy.add(module2)
except ValueError:
pass
if hasattr(module, 'referencedBy'):
for d in module.referencedBy:
pos = d.depends.index(module)
d.depends[pos] = module2
if not hasattr(module2, 'referencedBy'):
module2.referencedBy = []
module2.referencedBy.append(d)
if loaded:
loadedModules[lpos] = module2
# Start the uploaded modules
for m in loadedModules:
self.subroutine(self.loadmodule(m))
if failures:
raise ModuleLoadException('Following errors occurred during reloading, check log for more details:\n' + '\n'.join(failures)) | python | async def reload_modules(self, pathlist):
"""
Reload modules with a full path in the pathlist
"""
loadedModules = []
failures = []
for path in pathlist:
p, module = findModule(path, False)
if module is not None and hasattr(module, '_instance') and module._instance.state != ModuleLoadStateChanged.UNLOADED:
loadedModules.append(module)
# Unload all modules
ums = [ModuleLoadStateChanged.createMatcher(m, ModuleLoadStateChanged.UNLOADED) for m in loadedModules]
for m in loadedModules:
# Only unload the module itself, not its dependencies, since we will restart the module soon enough
self.subroutine(self.unloadmodule(m, True), False)
await self.wait_for_all(*ums)
# Group modules by package
grouped = {}
for path in pathlist:
dotpos = path.rfind('.')
if dotpos == -1:
raise ModuleLoadException('Must specify module with full path, including package name')
package = path[:dotpos]
classname = path[dotpos + 1:]
mlist = grouped.setdefault(package, [])
p, module = findModule(path, False)
mlist.append((classname, module))
for package, mlist in grouped.items():
# Reload each package only once
try:
p = sys.modules[package]
# Remove cache to ensure a clean import from source file
removeCache(p)
p = reload(p)
except KeyError:
try:
p = __import__(package, fromlist=[m[0] for m in mlist])
except Exception:
self._logger.warning('Failed to import a package: %r, resume others', package, exc_info = True)
failures.append('Failed to import: ' + package)
continue
except Exception:
self._logger.warning('Failed to import a package: %r, resume others', package, exc_info = True)
failures.append('Failed to import: ' + package)
continue
for cn, module in mlist:
try:
module2 = getattr(p, cn)
except AttributeError:
self._logger.warning('Cannot find module %r in package %r, resume others', package, cn)
failures.append('Failed to import: ' + package + '.' + cn)
continue
if module is not None and module is not module2:
# Update the references
try:
lpos = loadedModules.index(module)
loaded = True
except Exception:
loaded = False
for d in module.depends:
# The new reference is automatically added on import, only remove the old reference
d.referencedBy.remove(module)
if loaded and hasattr(d, '_instance'):
try:
d._instance.dependedBy.remove(module)
d._instance.dependedBy.add(module2)
except ValueError:
pass
if hasattr(module, 'referencedBy'):
for d in module.referencedBy:
pos = d.depends.index(module)
d.depends[pos] = module2
if not hasattr(module2, 'referencedBy'):
module2.referencedBy = []
module2.referencedBy.append(d)
if loaded:
loadedModules[lpos] = module2
# Start the uploaded modules
for m in loadedModules:
self.subroutine(self.loadmodule(m))
if failures:
raise ModuleLoadException('Following errors occurred during reloading, check log for more details:\n' + '\n'.join(failures)) | [
"async",
"def",
"reload_modules",
"(",
"self",
",",
"pathlist",
")",
":",
"loadedModules",
"=",
"[",
"]",
"failures",
"=",
"[",
"]",
"for",
"path",
"in",
"pathlist",
":",
"p",
",",
"module",
"=",
"findModule",
"(",
"path",
",",
"False",
")",
"if",
"module",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"module",
",",
"'_instance'",
")",
"and",
"module",
".",
"_instance",
".",
"state",
"!=",
"ModuleLoadStateChanged",
".",
"UNLOADED",
":",
"loadedModules",
".",
"append",
"(",
"module",
")",
"# Unload all modules",
"ums",
"=",
"[",
"ModuleLoadStateChanged",
".",
"createMatcher",
"(",
"m",
",",
"ModuleLoadStateChanged",
".",
"UNLOADED",
")",
"for",
"m",
"in",
"loadedModules",
"]",
"for",
"m",
"in",
"loadedModules",
":",
"# Only unload the module itself, not its dependencies, since we will restart the module soon enough",
"self",
".",
"subroutine",
"(",
"self",
".",
"unloadmodule",
"(",
"m",
",",
"True",
")",
",",
"False",
")",
"await",
"self",
".",
"wait_for_all",
"(",
"*",
"ums",
")",
"# Group modules by package",
"grouped",
"=",
"{",
"}",
"for",
"path",
"in",
"pathlist",
":",
"dotpos",
"=",
"path",
".",
"rfind",
"(",
"'.'",
")",
"if",
"dotpos",
"==",
"-",
"1",
":",
"raise",
"ModuleLoadException",
"(",
"'Must specify module with full path, including package name'",
")",
"package",
"=",
"path",
"[",
":",
"dotpos",
"]",
"classname",
"=",
"path",
"[",
"dotpos",
"+",
"1",
":",
"]",
"mlist",
"=",
"grouped",
".",
"setdefault",
"(",
"package",
",",
"[",
"]",
")",
"p",
",",
"module",
"=",
"findModule",
"(",
"path",
",",
"False",
")",
"mlist",
".",
"append",
"(",
"(",
"classname",
",",
"module",
")",
")",
"for",
"package",
",",
"mlist",
"in",
"grouped",
".",
"items",
"(",
")",
":",
"# Reload each package only once",
"try",
":",
"p",
"=",
"sys",
".",
"modules",
"[",
"package",
"]",
"# Remove cache to ensure a clean import from source file",
"removeCache",
"(",
"p",
")",
"p",
"=",
"reload",
"(",
"p",
")",
"except",
"KeyError",
":",
"try",
":",
"p",
"=",
"__import__",
"(",
"package",
",",
"fromlist",
"=",
"[",
"m",
"[",
"0",
"]",
"for",
"m",
"in",
"mlist",
"]",
")",
"except",
"Exception",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"'Failed to import a package: %r, resume others'",
",",
"package",
",",
"exc_info",
"=",
"True",
")",
"failures",
".",
"append",
"(",
"'Failed to import: '",
"+",
"package",
")",
"continue",
"except",
"Exception",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"'Failed to import a package: %r, resume others'",
",",
"package",
",",
"exc_info",
"=",
"True",
")",
"failures",
".",
"append",
"(",
"'Failed to import: '",
"+",
"package",
")",
"continue",
"for",
"cn",
",",
"module",
"in",
"mlist",
":",
"try",
":",
"module2",
"=",
"getattr",
"(",
"p",
",",
"cn",
")",
"except",
"AttributeError",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"'Cannot find module %r in package %r, resume others'",
",",
"package",
",",
"cn",
")",
"failures",
".",
"append",
"(",
"'Failed to import: '",
"+",
"package",
"+",
"'.'",
"+",
"cn",
")",
"continue",
"if",
"module",
"is",
"not",
"None",
"and",
"module",
"is",
"not",
"module2",
":",
"# Update the references",
"try",
":",
"lpos",
"=",
"loadedModules",
".",
"index",
"(",
"module",
")",
"loaded",
"=",
"True",
"except",
"Exception",
":",
"loaded",
"=",
"False",
"for",
"d",
"in",
"module",
".",
"depends",
":",
"# The new reference is automatically added on import, only remove the old reference",
"d",
".",
"referencedBy",
".",
"remove",
"(",
"module",
")",
"if",
"loaded",
"and",
"hasattr",
"(",
"d",
",",
"'_instance'",
")",
":",
"try",
":",
"d",
".",
"_instance",
".",
"dependedBy",
".",
"remove",
"(",
"module",
")",
"d",
".",
"_instance",
".",
"dependedBy",
".",
"add",
"(",
"module2",
")",
"except",
"ValueError",
":",
"pass",
"if",
"hasattr",
"(",
"module",
",",
"'referencedBy'",
")",
":",
"for",
"d",
"in",
"module",
".",
"referencedBy",
":",
"pos",
"=",
"d",
".",
"depends",
".",
"index",
"(",
"module",
")",
"d",
".",
"depends",
"[",
"pos",
"]",
"=",
"module2",
"if",
"not",
"hasattr",
"(",
"module2",
",",
"'referencedBy'",
")",
":",
"module2",
".",
"referencedBy",
"=",
"[",
"]",
"module2",
".",
"referencedBy",
".",
"append",
"(",
"d",
")",
"if",
"loaded",
":",
"loadedModules",
"[",
"lpos",
"]",
"=",
"module2",
"# Start the uploaded modules",
"for",
"m",
"in",
"loadedModules",
":",
"self",
".",
"subroutine",
"(",
"self",
".",
"loadmodule",
"(",
"m",
")",
")",
"if",
"failures",
":",
"raise",
"ModuleLoadException",
"(",
"'Following errors occurred during reloading, check log for more details:\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"failures",
")",
")"
] | Reload modules with a full path in the pathlist | [
"Reload",
"modules",
"with",
"a",
"full",
"path",
"in",
"the",
"pathlist"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L642-L723 |
hubo1016/vlcp | vlcp/server/module.py | ModuleLoader.get_module_by_name | def get_module_by_name(self, targetname):
"""
Return the module instance for a target name.
"""
if targetname == 'public':
target = None
elif not targetname not in self.activeModules:
raise KeyError('Module %r not exists or is not loaded' % (targetname,))
else:
target = self.activeModules[targetname]
return target | python | def get_module_by_name(self, targetname):
"""
Return the module instance for a target name.
"""
if targetname == 'public':
target = None
elif not targetname not in self.activeModules:
raise KeyError('Module %r not exists or is not loaded' % (targetname,))
else:
target = self.activeModules[targetname]
return target | [
"def",
"get_module_by_name",
"(",
"self",
",",
"targetname",
")",
":",
"if",
"targetname",
"==",
"'public'",
":",
"target",
"=",
"None",
"elif",
"not",
"targetname",
"not",
"in",
"self",
".",
"activeModules",
":",
"raise",
"KeyError",
"(",
"'Module %r not exists or is not loaded'",
"%",
"(",
"targetname",
",",
")",
")",
"else",
":",
"target",
"=",
"self",
".",
"activeModules",
"[",
"targetname",
"]",
"return",
"target"
] | Return the module instance for a target name. | [
"Return",
"the",
"module",
"instance",
"for",
"a",
"target",
"name",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L727-L737 |
hubo1016/vlcp | vlcp/config/config.py | configbase | def configbase(key):
"""
Decorator to set this class to configuration base class. A configuration base class
uses `<parentbase>.key.` for its configuration base, and uses `<parentbase>.key.default` for configuration mapping.
"""
def decorator(cls):
parent = cls.getConfigurableParent()
if parent is None:
parentbase = None
else:
parentbase = getattr(parent, 'configbase', None)
if parentbase is None:
base = key
else:
base = parentbase + '.' + key
cls.configbase = base
cls.configkey = base + '.default'
return cls
return decorator | python | def configbase(key):
"""
Decorator to set this class to configuration base class. A configuration base class
uses `<parentbase>.key.` for its configuration base, and uses `<parentbase>.key.default` for configuration mapping.
"""
def decorator(cls):
parent = cls.getConfigurableParent()
if parent is None:
parentbase = None
else:
parentbase = getattr(parent, 'configbase', None)
if parentbase is None:
base = key
else:
base = parentbase + '.' + key
cls.configbase = base
cls.configkey = base + '.default'
return cls
return decorator | [
"def",
"configbase",
"(",
"key",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"parent",
"=",
"cls",
".",
"getConfigurableParent",
"(",
")",
"if",
"parent",
"is",
"None",
":",
"parentbase",
"=",
"None",
"else",
":",
"parentbase",
"=",
"getattr",
"(",
"parent",
",",
"'configbase'",
",",
"None",
")",
"if",
"parentbase",
"is",
"None",
":",
"base",
"=",
"key",
"else",
":",
"base",
"=",
"parentbase",
"+",
"'.'",
"+",
"key",
"cls",
".",
"configbase",
"=",
"base",
"cls",
".",
"configkey",
"=",
"base",
"+",
"'.default'",
"return",
"cls",
"return",
"decorator"
] | Decorator to set this class to configuration base class. A configuration base class
uses `<parentbase>.key.` for its configuration base, and uses `<parentbase>.key.default` for configuration mapping. | [
"Decorator",
"to",
"set",
"this",
"class",
"to",
"configuration",
"base",
"class",
".",
"A",
"configuration",
"base",
"class",
"uses",
"<parentbase",
">",
".",
"key",
".",
"for",
"its",
"configuration",
"base",
"and",
"uses",
"<parentbase",
">",
".",
"key",
".",
"default",
"for",
"configuration",
"mapping",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L391-L409 |
hubo1016/vlcp | vlcp/config/config.py | config | def config(key):
"""
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration
base and configuration mapping.
"""
def decorator(cls):
parent = cls.getConfigurableParent()
if parent is None:
parentbase = None
else:
parentbase = getattr(parent, 'configbase', None)
if parentbase is None:
cls.configkey = key
else:
cls.configkey = parentbase + '.' + key
return cls
return decorator | python | def config(key):
"""
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration
base and configuration mapping.
"""
def decorator(cls):
parent = cls.getConfigurableParent()
if parent is None:
parentbase = None
else:
parentbase = getattr(parent, 'configbase', None)
if parentbase is None:
cls.configkey = key
else:
cls.configkey = parentbase + '.' + key
return cls
return decorator | [
"def",
"config",
"(",
"key",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"parent",
"=",
"cls",
".",
"getConfigurableParent",
"(",
")",
"if",
"parent",
"is",
"None",
":",
"parentbase",
"=",
"None",
"else",
":",
"parentbase",
"=",
"getattr",
"(",
"parent",
",",
"'configbase'",
",",
"None",
")",
"if",
"parentbase",
"is",
"None",
":",
"cls",
".",
"configkey",
"=",
"key",
"else",
":",
"cls",
".",
"configkey",
"=",
"parentbase",
"+",
"'.'",
"+",
"key",
"return",
"cls",
"return",
"decorator"
] | Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration
base and configuration mapping. | [
"Decorator",
"to",
"map",
"this",
"class",
"directly",
"to",
"a",
"configuration",
"node",
".",
"It",
"uses",
"<parentbase",
">",
".",
"key",
"for",
"configuration",
"base",
"and",
"configuration",
"mapping",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L411-L427 |
hubo1016/vlcp | vlcp/config/config.py | defaultconfig | def defaultconfig(cls):
"""
Generate a default configuration mapping bases on the class name. If this class does not have a
parent with `configbase` defined, it is set to a configuration base with
`configbase=<lowercase-name>` and `configkey=<lowercase-name>.default`; otherwise it inherits
`configbase` of its parent and set `configkey=<parentbase>.<lowercase-name>`
Refer to :ref::`configurations` for normal rules.
"""
parentbase = None
for p in cls.__bases__:
if issubclass(p, Configurable):
parentbase = getattr(p, 'configbase', None)
break
if parentbase is None:
base = cls.__name__.lower()
cls.configbase = base
cls.configkey = base + '.default'
else:
key = cls.__name__.lower()
#=======================================================================
# parentkeys = parentbase.split('.')
# for pk in parentkeys:
# if key.endswith(pk):
# key = key[0:-len(pk)]
# elif key.startswith(pk):
# key = key[len(pk):]
#=======================================================================
cls.configkey = parentbase + "." + key
return cls | python | def defaultconfig(cls):
"""
Generate a default configuration mapping bases on the class name. If this class does not have a
parent with `configbase` defined, it is set to a configuration base with
`configbase=<lowercase-name>` and `configkey=<lowercase-name>.default`; otherwise it inherits
`configbase` of its parent and set `configkey=<parentbase>.<lowercase-name>`
Refer to :ref::`configurations` for normal rules.
"""
parentbase = None
for p in cls.__bases__:
if issubclass(p, Configurable):
parentbase = getattr(p, 'configbase', None)
break
if parentbase is None:
base = cls.__name__.lower()
cls.configbase = base
cls.configkey = base + '.default'
else:
key = cls.__name__.lower()
#=======================================================================
# parentkeys = parentbase.split('.')
# for pk in parentkeys:
# if key.endswith(pk):
# key = key[0:-len(pk)]
# elif key.startswith(pk):
# key = key[len(pk):]
#=======================================================================
cls.configkey = parentbase + "." + key
return cls | [
"def",
"defaultconfig",
"(",
"cls",
")",
":",
"parentbase",
"=",
"None",
"for",
"p",
"in",
"cls",
".",
"__bases__",
":",
"if",
"issubclass",
"(",
"p",
",",
"Configurable",
")",
":",
"parentbase",
"=",
"getattr",
"(",
"p",
",",
"'configbase'",
",",
"None",
")",
"break",
"if",
"parentbase",
"is",
"None",
":",
"base",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"cls",
".",
"configbase",
"=",
"base",
"cls",
".",
"configkey",
"=",
"base",
"+",
"'.default'",
"else",
":",
"key",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"#=======================================================================",
"# parentkeys = parentbase.split('.')",
"# for pk in parentkeys:",
"# if key.endswith(pk):",
"# key = key[0:-len(pk)]",
"# elif key.startswith(pk):",
"# key = key[len(pk):]",
"#=======================================================================",
"cls",
".",
"configkey",
"=",
"parentbase",
"+",
"\".\"",
"+",
"key",
"return",
"cls"
] | Generate a default configuration mapping bases on the class name. If this class does not have a
parent with `configbase` defined, it is set to a configuration base with
`configbase=<lowercase-name>` and `configkey=<lowercase-name>.default`; otherwise it inherits
`configbase` of its parent and set `configkey=<parentbase>.<lowercase-name>`
Refer to :ref::`configurations` for normal rules. | [
"Generate",
"a",
"default",
"configuration",
"mapping",
"bases",
"on",
"the",
"class",
"name",
".",
"If",
"this",
"class",
"does",
"not",
"have",
"a",
"parent",
"with",
"configbase",
"defined",
"it",
"is",
"set",
"to",
"a",
"configuration",
"base",
"with",
"configbase",
"=",
"<lowercase",
"-",
"name",
">",
"and",
"configkey",
"=",
"<lowercase",
"-",
"name",
">",
".",
"default",
";",
"otherwise",
"it",
"inherits",
"configbase",
"of",
"its",
"parent",
"and",
"set",
"configkey",
"=",
"<parentbase",
">",
".",
"<lowercase",
"-",
"name",
">",
"Refer",
"to",
":",
"ref",
"::",
"configurations",
"for",
"normal",
"rules",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L429-L458 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.config_keys | def config_keys(self, sortkey = False):
"""
Return all configuration keys in this node, including configurations on children nodes.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
for k,v in items:
if isinstance(v, ConfigTree):
for k2 in v.config_keys(sortkey):
yield k + '.' + k2
else:
yield k | python | def config_keys(self, sortkey = False):
"""
Return all configuration keys in this node, including configurations on children nodes.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
for k,v in items:
if isinstance(v, ConfigTree):
for k2 in v.config_keys(sortkey):
yield k + '.' + k2
else:
yield k | [
"def",
"config_keys",
"(",
"self",
",",
"sortkey",
"=",
"False",
")",
":",
"if",
"sortkey",
":",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"else",
":",
"items",
"=",
"self",
".",
"items",
"(",
")",
"for",
"k",
",",
"v",
"in",
"items",
":",
"if",
"isinstance",
"(",
"v",
",",
"ConfigTree",
")",
":",
"for",
"k2",
"in",
"v",
".",
"config_keys",
"(",
"sortkey",
")",
":",
"yield",
"k",
"+",
"'.'",
"+",
"k2",
"else",
":",
"yield",
"k"
] | Return all configuration keys in this node, including configurations on children nodes. | [
"Return",
"all",
"configuration",
"keys",
"in",
"this",
"node",
"including",
"configurations",
"on",
"children",
"nodes",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L36-L49 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.config_items | def config_items(self, sortkey = False):
"""
Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
for k,v in items:
if isinstance(v, ConfigTree):
for k2,v2 in v.config_items(sortkey):
yield (k + '.' + k2, v2)
else:
yield (k,v) | python | def config_items(self, sortkey = False):
"""
Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
for k,v in items:
if isinstance(v, ConfigTree):
for k2,v2 in v.config_items(sortkey):
yield (k + '.' + k2, v2)
else:
yield (k,v) | [
"def",
"config_items",
"(",
"self",
",",
"sortkey",
"=",
"False",
")",
":",
"if",
"sortkey",
":",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"else",
":",
"items",
"=",
"self",
".",
"items",
"(",
")",
"for",
"k",
",",
"v",
"in",
"items",
":",
"if",
"isinstance",
"(",
"v",
",",
"ConfigTree",
")",
":",
"for",
"k2",
",",
"v2",
"in",
"v",
".",
"config_items",
"(",
"sortkey",
")",
":",
"yield",
"(",
"k",
"+",
"'.'",
"+",
"k2",
",",
"v2",
")",
"else",
":",
"yield",
"(",
"k",
",",
"v",
")"
] | Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes. | [
"Return",
"all",
"(",
"key",
"value",
")",
"tuples",
"for",
"configurations",
"in",
"this",
"node",
"including",
"configurations",
"on",
"children",
"nodes",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L50-L63 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.config_value_keys | def config_value_keys(self, sortkey = False):
"""
Return configuration keys directly stored in this node. Configurations in child nodes are not included.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
return (k for k,v in items if not isinstance(v,ConfigTree)) | python | def config_value_keys(self, sortkey = False):
"""
Return configuration keys directly stored in this node. Configurations in child nodes are not included.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
return (k for k,v in items if not isinstance(v,ConfigTree)) | [
"def",
"config_value_keys",
"(",
"self",
",",
"sortkey",
"=",
"False",
")",
":",
"if",
"sortkey",
":",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"else",
":",
"items",
"=",
"self",
".",
"items",
"(",
")",
"return",
"(",
"k",
"for",
"k",
",",
"v",
"in",
"items",
"if",
"not",
"isinstance",
"(",
"v",
",",
"ConfigTree",
")",
")"
] | Return configuration keys directly stored in this node. Configurations in child nodes are not included. | [
"Return",
"configuration",
"keys",
"directly",
"stored",
"in",
"this",
"node",
".",
"Configurations",
"in",
"child",
"nodes",
"are",
"not",
"included",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L64-L72 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.loadconfig | def loadconfig(self, keysuffix, obj):
"""
Copy all configurations from this node into obj
"""
subtree = self.get(keysuffix)
if subtree is not None and isinstance(subtree, ConfigTree):
for k,v in subtree.items():
if isinstance(v, ConfigTree):
if hasattr(obj, k) and not isinstance(getattr(obj, k), ConfigTree):
v.loadconfig(getattr(obj,k))
else:
setattr(obj, k, v)
elif not hasattr(obj, k):
setattr(obj, k, v) | python | def loadconfig(self, keysuffix, obj):
"""
Copy all configurations from this node into obj
"""
subtree = self.get(keysuffix)
if subtree is not None and isinstance(subtree, ConfigTree):
for k,v in subtree.items():
if isinstance(v, ConfigTree):
if hasattr(obj, k) and not isinstance(getattr(obj, k), ConfigTree):
v.loadconfig(getattr(obj,k))
else:
setattr(obj, k, v)
elif not hasattr(obj, k):
setattr(obj, k, v) | [
"def",
"loadconfig",
"(",
"self",
",",
"keysuffix",
",",
"obj",
")",
":",
"subtree",
"=",
"self",
".",
"get",
"(",
"keysuffix",
")",
"if",
"subtree",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"subtree",
",",
"ConfigTree",
")",
":",
"for",
"k",
",",
"v",
"in",
"subtree",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"ConfigTree",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"k",
")",
"and",
"not",
"isinstance",
"(",
"getattr",
"(",
"obj",
",",
"k",
")",
",",
"ConfigTree",
")",
":",
"v",
".",
"loadconfig",
"(",
"getattr",
"(",
"obj",
",",
"k",
")",
")",
"else",
":",
"setattr",
"(",
"obj",
",",
"k",
",",
"v",
")",
"elif",
"not",
"hasattr",
"(",
"obj",
",",
"k",
")",
":",
"setattr",
"(",
"obj",
",",
"k",
",",
"v",
")"
] | Copy all configurations from this node into obj | [
"Copy",
"all",
"configurations",
"from",
"this",
"node",
"into",
"obj"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L82-L95 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.withconfig | def withconfig(self, keysuffix):
"""
Load configurations with this decorator
"""
def decorator(cls):
return self.loadconfig(keysuffix, cls)
return decorator | python | def withconfig(self, keysuffix):
"""
Load configurations with this decorator
"""
def decorator(cls):
return self.loadconfig(keysuffix, cls)
return decorator | [
"def",
"withconfig",
"(",
"self",
",",
"keysuffix",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"return",
"self",
".",
"loadconfig",
"(",
"keysuffix",
",",
"cls",
")",
"return",
"decorator"
] | Load configurations with this decorator | [
"Load",
"configurations",
"with",
"this",
"decorator"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L96-L102 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.gettree | def gettree(self, key, create = False):
"""
Get a subtree node from the key (path relative to this node)
"""
tree, _ = self._getsubitem(key + '.tmp', create)
return tree | python | def gettree(self, key, create = False):
"""
Get a subtree node from the key (path relative to this node)
"""
tree, _ = self._getsubitem(key + '.tmp', create)
return tree | [
"def",
"gettree",
"(",
"self",
",",
"key",
",",
"create",
"=",
"False",
")",
":",
"tree",
",",
"_",
"=",
"self",
".",
"_getsubitem",
"(",
"key",
"+",
"'.tmp'",
",",
"create",
")",
"return",
"tree"
] | Get a subtree node from the key (path relative to this node) | [
"Get",
"a",
"subtree",
"node",
"from",
"the",
"key",
"(",
"path",
"relative",
"to",
"this",
"node",
")"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L108-L113 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.get | def get(self, key, defaultvalue = None):
"""
Support dict-like get (return a default value if not found)
"""
(t, k) = self._getsubitem(key, False)
if t is None:
return defaultvalue
else:
return t.__dict__.get(k, defaultvalue) | python | def get(self, key, defaultvalue = None):
"""
Support dict-like get (return a default value if not found)
"""
(t, k) = self._getsubitem(key, False)
if t is None:
return defaultvalue
else:
return t.__dict__.get(k, defaultvalue) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"defaultvalue",
"=",
"None",
")",
":",
"(",
"t",
",",
"k",
")",
"=",
"self",
".",
"_getsubitem",
"(",
"key",
",",
"False",
")",
"if",
"t",
"is",
"None",
":",
"return",
"defaultvalue",
"else",
":",
"return",
"t",
".",
"__dict__",
".",
"get",
"(",
"k",
",",
"defaultvalue",
")"
] | Support dict-like get (return a default value if not found) | [
"Support",
"dict",
"-",
"like",
"get",
"(",
"return",
"a",
"default",
"value",
"if",
"not",
"found",
")"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L163-L171 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.setdefault | def setdefault(self, key, defaultvalue = None):
"""
Support dict-like setdefault (create if not existed)
"""
(t, k) = self._getsubitem(key, True)
return t.__dict__.setdefault(k, defaultvalue) | python | def setdefault(self, key, defaultvalue = None):
"""
Support dict-like setdefault (create if not existed)
"""
(t, k) = self._getsubitem(key, True)
return t.__dict__.setdefault(k, defaultvalue) | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"defaultvalue",
"=",
"None",
")",
":",
"(",
"t",
",",
"k",
")",
"=",
"self",
".",
"_getsubitem",
"(",
"key",
",",
"True",
")",
"return",
"t",
".",
"__dict__",
".",
"setdefault",
"(",
"k",
",",
"defaultvalue",
")"
] | Support dict-like setdefault (create if not existed) | [
"Support",
"dict",
"-",
"like",
"setdefault",
"(",
"create",
"if",
"not",
"existed",
")"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L172-L177 |
hubo1016/vlcp | vlcp/config/config.py | ConfigTree.todict | def todict(self):
"""
Convert this node to a dictionary tree.
"""
dict_entry = []
for k,v in self.items():
if isinstance(v, ConfigTree):
dict_entry.append((k, v.todict()))
else:
dict_entry.append((k, v))
return dict(dict_entry) | python | def todict(self):
"""
Convert this node to a dictionary tree.
"""
dict_entry = []
for k,v in self.items():
if isinstance(v, ConfigTree):
dict_entry.append((k, v.todict()))
else:
dict_entry.append((k, v))
return dict(dict_entry) | [
"def",
"todict",
"(",
"self",
")",
":",
"dict_entry",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"ConfigTree",
")",
":",
"dict_entry",
".",
"append",
"(",
"(",
"k",
",",
"v",
".",
"todict",
"(",
")",
")",
")",
"else",
":",
"dict_entry",
".",
"append",
"(",
"(",
"k",
",",
"v",
")",
")",
"return",
"dict",
"(",
"dict_entry",
")"
] | Convert this node to a dictionary tree. | [
"Convert",
"this",
"node",
"to",
"a",
"dictionary",
"tree",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L192-L202 |
hubo1016/vlcp | vlcp/config/config.py | Manager.loadfromfile | def loadfromfile(self, filelike):
"""
Read configurations from a file-like object, or a sequence of strings. Old values are not
cleared, if you want to reload the configurations completely, you should call `clear()`
before using `load*` methods.
"""
line_format = re.compile(r'((?:[a-zA-Z][a-zA-Z0-9_]*\.)*[a-zA-Z][a-zA-Z0-9_]*)\s*=\s*')
space = re.compile(r'\s')
line_no = 0
# Suport multi-line data
line_buffer = []
line_key = None
last_line_no = None
for l in filelike:
line_no += 1
ls = l.strip()
# If there is a # in start, the whole line is remarked.
# ast.literal_eval already processed any # after '='.
if not ls or ls.startswith('#'):
continue
if space.match(l):
if not line_key:
# First line cannot start with space
raise ValueError('Error format in line %d: first line cannot start with space%s\n' % (line_no, l))
line_buffer.append(l)
else:
if line_key:
# Process buffered lines
try:
value = ast.literal_eval(''.join(line_buffer))
except Exception:
typ, val, tb = sys.exc_info()
raise ValueError('Error format in line %d(%s: %s):\n%s' % (last_line_no, typ.__name__, str(val), ''.join(line_buffer)))
self[line_key] = value
# First line
m = line_format.match(l)
if not m:
raise ValueError('Error format in line %d:\n%s' % (line_no, l))
line_key = m.group(1)
last_line_no = line_no
del line_buffer[:]
line_buffer.append(l[m.end():])
if line_key:
# Process buffered lines
try:
value = ast.literal_eval(''.join(line_buffer))
except Exception:
typ, val, tb = sys.exc_info()
raise ValueError('Error format in line %d(%s: %s):\n%s' % (last_line_no, typ.__name__, str(val), ''.join(line_buffer)))
self[line_key] = value | python | def loadfromfile(self, filelike):
"""
Read configurations from a file-like object, or a sequence of strings. Old values are not
cleared, if you want to reload the configurations completely, you should call `clear()`
before using `load*` methods.
"""
line_format = re.compile(r'((?:[a-zA-Z][a-zA-Z0-9_]*\.)*[a-zA-Z][a-zA-Z0-9_]*)\s*=\s*')
space = re.compile(r'\s')
line_no = 0
# Suport multi-line data
line_buffer = []
line_key = None
last_line_no = None
for l in filelike:
line_no += 1
ls = l.strip()
# If there is a # in start, the whole line is remarked.
# ast.literal_eval already processed any # after '='.
if not ls or ls.startswith('#'):
continue
if space.match(l):
if not line_key:
# First line cannot start with space
raise ValueError('Error format in line %d: first line cannot start with space%s\n' % (line_no, l))
line_buffer.append(l)
else:
if line_key:
# Process buffered lines
try:
value = ast.literal_eval(''.join(line_buffer))
except Exception:
typ, val, tb = sys.exc_info()
raise ValueError('Error format in line %d(%s: %s):\n%s' % (last_line_no, typ.__name__, str(val), ''.join(line_buffer)))
self[line_key] = value
# First line
m = line_format.match(l)
if not m:
raise ValueError('Error format in line %d:\n%s' % (line_no, l))
line_key = m.group(1)
last_line_no = line_no
del line_buffer[:]
line_buffer.append(l[m.end():])
if line_key:
# Process buffered lines
try:
value = ast.literal_eval(''.join(line_buffer))
except Exception:
typ, val, tb = sys.exc_info()
raise ValueError('Error format in line %d(%s: %s):\n%s' % (last_line_no, typ.__name__, str(val), ''.join(line_buffer)))
self[line_key] = value | [
"def",
"loadfromfile",
"(",
"self",
",",
"filelike",
")",
":",
"line_format",
"=",
"re",
".",
"compile",
"(",
"r'((?:[a-zA-Z][a-zA-Z0-9_]*\\.)*[a-zA-Z][a-zA-Z0-9_]*)\\s*=\\s*'",
")",
"space",
"=",
"re",
".",
"compile",
"(",
"r'\\s'",
")",
"line_no",
"=",
"0",
"# Suport multi-line data",
"line_buffer",
"=",
"[",
"]",
"line_key",
"=",
"None",
"last_line_no",
"=",
"None",
"for",
"l",
"in",
"filelike",
":",
"line_no",
"+=",
"1",
"ls",
"=",
"l",
".",
"strip",
"(",
")",
"# If there is a # in start, the whole line is remarked.",
"# ast.literal_eval already processed any # after '='.",
"if",
"not",
"ls",
"or",
"ls",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"if",
"space",
".",
"match",
"(",
"l",
")",
":",
"if",
"not",
"line_key",
":",
"# First line cannot start with space",
"raise",
"ValueError",
"(",
"'Error format in line %d: first line cannot start with space%s\\n'",
"%",
"(",
"line_no",
",",
"l",
")",
")",
"line_buffer",
".",
"append",
"(",
"l",
")",
"else",
":",
"if",
"line_key",
":",
"# Process buffered lines",
"try",
":",
"value",
"=",
"ast",
".",
"literal_eval",
"(",
"''",
".",
"join",
"(",
"line_buffer",
")",
")",
"except",
"Exception",
":",
"typ",
",",
"val",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise",
"ValueError",
"(",
"'Error format in line %d(%s: %s):\\n%s'",
"%",
"(",
"last_line_no",
",",
"typ",
".",
"__name__",
",",
"str",
"(",
"val",
")",
",",
"''",
".",
"join",
"(",
"line_buffer",
")",
")",
")",
"self",
"[",
"line_key",
"]",
"=",
"value",
"# First line",
"m",
"=",
"line_format",
".",
"match",
"(",
"l",
")",
"if",
"not",
"m",
":",
"raise",
"ValueError",
"(",
"'Error format in line %d:\\n%s'",
"%",
"(",
"line_no",
",",
"l",
")",
")",
"line_key",
"=",
"m",
".",
"group",
"(",
"1",
")",
"last_line_no",
"=",
"line_no",
"del",
"line_buffer",
"[",
":",
"]",
"line_buffer",
".",
"append",
"(",
"l",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
")",
"if",
"line_key",
":",
"# Process buffered lines",
"try",
":",
"value",
"=",
"ast",
".",
"literal_eval",
"(",
"''",
".",
"join",
"(",
"line_buffer",
")",
")",
"except",
"Exception",
":",
"typ",
",",
"val",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise",
"ValueError",
"(",
"'Error format in line %d(%s: %s):\\n%s'",
"%",
"(",
"last_line_no",
",",
"typ",
".",
"__name__",
",",
"str",
"(",
"val",
")",
",",
"''",
".",
"join",
"(",
"line_buffer",
")",
")",
")",
"self",
"[",
"line_key",
"]",
"=",
"value"
] | Read configurations from a file-like object, or a sequence of strings. Old values are not
cleared, if you want to reload the configurations completely, you should call `clear()`
before using `load*` methods. | [
"Read",
"configurations",
"from",
"a",
"file",
"-",
"like",
"object",
"or",
"a",
"sequence",
"of",
"strings",
".",
"Old",
"values",
"are",
"not",
"cleared",
"if",
"you",
"want",
"to",
"reload",
"the",
"configurations",
"completely",
"you",
"should",
"call",
"clear",
"()",
"before",
"using",
"load",
"*",
"methods",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L210-L259 |
hubo1016/vlcp | vlcp/config/config.py | Manager.save | def save(self, sortkey = True):
"""
Save configurations to a list of strings
"""
return [k + '=' + repr(v) for k,v in self.config_items(sortkey)] | python | def save(self, sortkey = True):
"""
Save configurations to a list of strings
"""
return [k + '=' + repr(v) for k,v in self.config_items(sortkey)] | [
"def",
"save",
"(",
"self",
",",
"sortkey",
"=",
"True",
")",
":",
"return",
"[",
"k",
"+",
"'='",
"+",
"repr",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"config_items",
"(",
"sortkey",
")",
"]"
] | Save configurations to a list of strings | [
"Save",
"configurations",
"to",
"a",
"list",
"of",
"strings"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L271-L275 |
hubo1016/vlcp | vlcp/config/config.py | Manager.savetostr | def savetostr(self, sortkey = True):
"""
Save configurations to a single string
"""
return ''.join(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | python | def savetostr(self, sortkey = True):
"""
Save configurations to a single string
"""
return ''.join(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | [
"def",
"savetostr",
"(",
"self",
",",
"sortkey",
"=",
"True",
")",
":",
"return",
"''",
".",
"join",
"(",
"k",
"+",
"'='",
"+",
"repr",
"(",
"v",
")",
"+",
"'\\n'",
"for",
"k",
",",
"v",
"in",
"self",
".",
"config_items",
"(",
"sortkey",
")",
")"
] | Save configurations to a single string | [
"Save",
"configurations",
"to",
"a",
"single",
"string"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L276-L280 |
hubo1016/vlcp | vlcp/config/config.py | Manager.savetofile | def savetofile(self, filelike, sortkey = True):
"""
Save configurations to a file-like object which supports `writelines`
"""
filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | python | def savetofile(self, filelike, sortkey = True):
"""
Save configurations to a file-like object which supports `writelines`
"""
filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | [
"def",
"savetofile",
"(",
"self",
",",
"filelike",
",",
"sortkey",
"=",
"True",
")",
":",
"filelike",
".",
"writelines",
"(",
"k",
"+",
"'='",
"+",
"repr",
"(",
"v",
")",
"+",
"'\\n'",
"for",
"k",
",",
"v",
"in",
"self",
".",
"config_items",
"(",
"sortkey",
")",
")"
] | Save configurations to a file-like object which supports `writelines` | [
"Save",
"configurations",
"to",
"a",
"file",
"-",
"like",
"object",
"which",
"supports",
"writelines"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L281-L285 |
hubo1016/vlcp | vlcp/config/config.py | Manager.saveto | def saveto(self, path, sortkey = True):
"""
Save configurations to path
"""
with open(path, 'w') as f:
self.savetofile(f, sortkey) | python | def saveto(self, path, sortkey = True):
"""
Save configurations to path
"""
with open(path, 'w') as f:
self.savetofile(f, sortkey) | [
"def",
"saveto",
"(",
"self",
",",
"path",
",",
"sortkey",
"=",
"True",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"self",
".",
"savetofile",
"(",
"f",
",",
"sortkey",
")"
] | Save configurations to path | [
"Save",
"configurations",
"to",
"path"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L286-L291 |
hubo1016/vlcp | vlcp/config/config.py | Configurable.getConfigurableParent | def getConfigurableParent(cls):
"""
Return the parent from which this class inherits configurations
"""
for p in cls.__bases__:
if isinstance(p, Configurable) and p is not Configurable:
return p
return None | python | def getConfigurableParent(cls):
"""
Return the parent from which this class inherits configurations
"""
for p in cls.__bases__:
if isinstance(p, Configurable) and p is not Configurable:
return p
return None | [
"def",
"getConfigurableParent",
"(",
"cls",
")",
":",
"for",
"p",
"in",
"cls",
".",
"__bases__",
":",
"if",
"isinstance",
"(",
"p",
",",
"Configurable",
")",
"and",
"p",
"is",
"not",
"Configurable",
":",
"return",
"p",
"return",
"None"
] | Return the parent from which this class inherits configurations | [
"Return",
"the",
"parent",
"from",
"which",
"this",
"class",
"inherits",
"configurations"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L346-L353 |
hubo1016/vlcp | vlcp/config/config.py | Configurable.getConfigRoot | def getConfigRoot(cls, create = False):
"""
Return the mapped configuration root node
"""
try:
return manager.gettree(getattr(cls, 'configkey'), create)
except AttributeError:
return None | python | def getConfigRoot(cls, create = False):
"""
Return the mapped configuration root node
"""
try:
return manager.gettree(getattr(cls, 'configkey'), create)
except AttributeError:
return None | [
"def",
"getConfigRoot",
"(",
"cls",
",",
"create",
"=",
"False",
")",
":",
"try",
":",
"return",
"manager",
".",
"gettree",
"(",
"getattr",
"(",
"cls",
",",
"'configkey'",
")",
",",
"create",
")",
"except",
"AttributeError",
":",
"return",
"None"
] | Return the mapped configuration root node | [
"Return",
"the",
"mapped",
"configuration",
"root",
"node"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L355-L362 |
hubo1016/vlcp | vlcp/config/config.py | Configurable.config_value_keys | def config_value_keys(self, sortkey = False):
"""
Return all mapped configuration keys for this object
"""
ret = set()
cls = type(self)
while True:
root = cls.getConfigRoot()
if root:
ret = ret.union(set(root.config_value_keys()))
parent = None
for c in cls.__bases__:
if issubclass(c, Configurable):
parent = c
if parent is None:
break
cls = parent
if sortkey:
return sorted(list(ret))
else:
return list(ret) | python | def config_value_keys(self, sortkey = False):
"""
Return all mapped configuration keys for this object
"""
ret = set()
cls = type(self)
while True:
root = cls.getConfigRoot()
if root:
ret = ret.union(set(root.config_value_keys()))
parent = None
for c in cls.__bases__:
if issubclass(c, Configurable):
parent = c
if parent is None:
break
cls = parent
if sortkey:
return sorted(list(ret))
else:
return list(ret) | [
"def",
"config_value_keys",
"(",
"self",
",",
"sortkey",
"=",
"False",
")",
":",
"ret",
"=",
"set",
"(",
")",
"cls",
"=",
"type",
"(",
"self",
")",
"while",
"True",
":",
"root",
"=",
"cls",
".",
"getConfigRoot",
"(",
")",
"if",
"root",
":",
"ret",
"=",
"ret",
".",
"union",
"(",
"set",
"(",
"root",
".",
"config_value_keys",
"(",
")",
")",
")",
"parent",
"=",
"None",
"for",
"c",
"in",
"cls",
".",
"__bases__",
":",
"if",
"issubclass",
"(",
"c",
",",
"Configurable",
")",
":",
"parent",
"=",
"c",
"if",
"parent",
"is",
"None",
":",
"break",
"cls",
"=",
"parent",
"if",
"sortkey",
":",
"return",
"sorted",
"(",
"list",
"(",
"ret",
")",
")",
"else",
":",
"return",
"list",
"(",
"ret",
")"
] | Return all mapped configuration keys for this object | [
"Return",
"all",
"mapped",
"configuration",
"keys",
"for",
"this",
"object"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L363-L383 |
hubo1016/vlcp | vlcp/config/config.py | Configurable.config_value_items | def config_value_items(self, sortkey = False):
"""
Return `(key, value)` tuples for all mapped configurations for this object
"""
return ((k, getattr(self, k)) for k in self.config_value_keys(sortkey)) | python | def config_value_items(self, sortkey = False):
"""
Return `(key, value)` tuples for all mapped configurations for this object
"""
return ((k, getattr(self, k)) for k in self.config_value_keys(sortkey)) | [
"def",
"config_value_items",
"(",
"self",
",",
"sortkey",
"=",
"False",
")",
":",
"return",
"(",
"(",
"k",
",",
"getattr",
"(",
"self",
",",
"k",
")",
")",
"for",
"k",
"in",
"self",
".",
"config_value_keys",
"(",
"sortkey",
")",
")"
] | Return `(key, value)` tuples for all mapped configurations for this object | [
"Return",
"(",
"key",
"value",
")",
"tuples",
"for",
"all",
"mapped",
"configurations",
"for",
"this",
"object"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L385-L389 |
hubo1016/vlcp | vlcp/server/server.py | main | def main(configpath = None, startup = None, daemon = False, pidfile = None, fork = None):
"""
The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
is used; if `server.startup` is not configured, any module defined or imported
into __main__ is loaded.
:param daemon: if True, use python-daemon to fork and start at background. `python-daemon` must be
installed::
pip install python-daemon
:param pidfile: if daemon=True, this file is used for the pidfile.
:param fork: use extra fork to start multiple instances
"""
if configpath is not None:
manager.loadfrom(configpath)
if startup is not None:
manager['server.startup'] = startup
if not manager.get('server.startup'):
# No startup modules, try to load from __main__
startup = []
import __main__
for k in dir(__main__):
m = getattr(__main__, k)
if isinstance(m, type) and issubclass(m, Module) and m is not Module:
startup.append('__main__.' + k)
manager['server.startup'] = startup
if fork is not None and fork > 1:
if not hasattr(os, 'fork'):
raise ValueError('Fork is not supported in this operating system.')
def start_process():
s = Server()
s.serve()
def main_process():
if fork is not None and fork > 1:
import multiprocessing
from time import sleep
sub_procs = []
for i in range(0, fork):
p = multiprocessing.Process(target = start_process)
sub_procs.append(p)
for i in range(0, fork):
sub_procs[i].start()
try:
import signal
def except_return(sig, frame):
raise SystemExit
signal.signal(signal.SIGTERM, except_return)
signal.signal(signal.SIGINT, except_return)
if hasattr(signal, 'SIGHUP'):
signal.signal(signal.SIGHUP, except_return)
while True:
sleep(2)
for i in range(0, fork):
if sub_procs[i].is_alive():
break
else:
break
finally:
for i in range(0, fork):
if sub_procs[i].is_alive():
sub_procs[i].terminate()
for i in range(0, fork):
sub_procs[i].join()
else:
start_process()
if daemon:
import daemon
if not pidfile:
pidfile = manager.get('daemon.pidfile')
uid = manager.get('daemon.uid')
gid = manager.get('daemon.gid')
if gid is None:
group = manager.get('daemon.group')
if group is not None:
import grp
gid = grp.getgrnam(group)[2]
if uid is None:
import pwd
user = manager.get('daemon.user')
if user is not None:
user_pw = pwd.getpwnam(user)
uid = user_pw.pw_uid
if gid is None:
gid = user_pw.pw_gid
if uid is not None and gid is None:
import pwd
gid = pwd.getpwuid(uid).pw_gid
if pidfile:
import fcntl
class PidLocker(object):
def __init__(self, path):
self.filepath = path
self.fd = None
def __enter__(self):
# Create pid file
self.fd = os.open(pidfile, os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o644)
fcntl.lockf(self.fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
os.write(self.fd, str(os.getpid()).encode('ascii'))
os.fsync(self.fd)
def __exit__(self, typ, val, tb):
if self.fd:
try:
fcntl.lockf(self.fd, fcntl.LOCK_UN)
except Exception:
pass
os.close(self.fd)
self.fd = None
locker = PidLocker(pidfile)
else:
locker = None
import sys
# Module loading is related to current path, add it to sys.path
cwd = os.getcwd()
if cwd not in sys.path:
sys.path.append(cwd)
# Fix path issues on already-loaded modules
for m in sys.modules.values():
if getattr(m, '__path__', None):
m.__path__ = [os.path.abspath(p) for p in m.__path__]
# __file__ is used for module-relative resource locate
if getattr(m, '__file__', None):
m.__file__ = os.path.abspath(m.__file__)
configs = {'gid':gid,'uid':uid,'pidfile':locker}
config_filters = ['chroot_directory', 'working_directory', 'umask', 'detach_process',
'prevent_core']
if hasattr(manager, 'daemon'):
configs.update((k,v) for k,v in manager.daemon.config_value_items() if k in config_filters)
if not hasattr(os, 'initgroups'):
configs['initgroups'] = False
with daemon.DaemonContext(**configs):
main_process()
else:
main_process() | python | def main(configpath = None, startup = None, daemon = False, pidfile = None, fork = None):
"""
The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
is used; if `server.startup` is not configured, any module defined or imported
into __main__ is loaded.
:param daemon: if True, use python-daemon to fork and start at background. `python-daemon` must be
installed::
pip install python-daemon
:param pidfile: if daemon=True, this file is used for the pidfile.
:param fork: use extra fork to start multiple instances
"""
if configpath is not None:
manager.loadfrom(configpath)
if startup is not None:
manager['server.startup'] = startup
if not manager.get('server.startup'):
# No startup modules, try to load from __main__
startup = []
import __main__
for k in dir(__main__):
m = getattr(__main__, k)
if isinstance(m, type) and issubclass(m, Module) and m is not Module:
startup.append('__main__.' + k)
manager['server.startup'] = startup
if fork is not None and fork > 1:
if not hasattr(os, 'fork'):
raise ValueError('Fork is not supported in this operating system.')
def start_process():
s = Server()
s.serve()
def main_process():
if fork is not None and fork > 1:
import multiprocessing
from time import sleep
sub_procs = []
for i in range(0, fork):
p = multiprocessing.Process(target = start_process)
sub_procs.append(p)
for i in range(0, fork):
sub_procs[i].start()
try:
import signal
def except_return(sig, frame):
raise SystemExit
signal.signal(signal.SIGTERM, except_return)
signal.signal(signal.SIGINT, except_return)
if hasattr(signal, 'SIGHUP'):
signal.signal(signal.SIGHUP, except_return)
while True:
sleep(2)
for i in range(0, fork):
if sub_procs[i].is_alive():
break
else:
break
finally:
for i in range(0, fork):
if sub_procs[i].is_alive():
sub_procs[i].terminate()
for i in range(0, fork):
sub_procs[i].join()
else:
start_process()
if daemon:
import daemon
if not pidfile:
pidfile = manager.get('daemon.pidfile')
uid = manager.get('daemon.uid')
gid = manager.get('daemon.gid')
if gid is None:
group = manager.get('daemon.group')
if group is not None:
import grp
gid = grp.getgrnam(group)[2]
if uid is None:
import pwd
user = manager.get('daemon.user')
if user is not None:
user_pw = pwd.getpwnam(user)
uid = user_pw.pw_uid
if gid is None:
gid = user_pw.pw_gid
if uid is not None and gid is None:
import pwd
gid = pwd.getpwuid(uid).pw_gid
if pidfile:
import fcntl
class PidLocker(object):
def __init__(self, path):
self.filepath = path
self.fd = None
def __enter__(self):
# Create pid file
self.fd = os.open(pidfile, os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o644)
fcntl.lockf(self.fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
os.write(self.fd, str(os.getpid()).encode('ascii'))
os.fsync(self.fd)
def __exit__(self, typ, val, tb):
if self.fd:
try:
fcntl.lockf(self.fd, fcntl.LOCK_UN)
except Exception:
pass
os.close(self.fd)
self.fd = None
locker = PidLocker(pidfile)
else:
locker = None
import sys
# Module loading is related to current path, add it to sys.path
cwd = os.getcwd()
if cwd not in sys.path:
sys.path.append(cwd)
# Fix path issues on already-loaded modules
for m in sys.modules.values():
if getattr(m, '__path__', None):
m.__path__ = [os.path.abspath(p) for p in m.__path__]
# __file__ is used for module-relative resource locate
if getattr(m, '__file__', None):
m.__file__ = os.path.abspath(m.__file__)
configs = {'gid':gid,'uid':uid,'pidfile':locker}
config_filters = ['chroot_directory', 'working_directory', 'umask', 'detach_process',
'prevent_core']
if hasattr(manager, 'daemon'):
configs.update((k,v) for k,v in manager.daemon.config_value_items() if k in config_filters)
if not hasattr(os, 'initgroups'):
configs['initgroups'] = False
with daemon.DaemonContext(**configs):
main_process()
else:
main_process() | [
"def",
"main",
"(",
"configpath",
"=",
"None",
",",
"startup",
"=",
"None",
",",
"daemon",
"=",
"False",
",",
"pidfile",
"=",
"None",
",",
"fork",
"=",
"None",
")",
":",
"if",
"configpath",
"is",
"not",
"None",
":",
"manager",
".",
"loadfrom",
"(",
"configpath",
")",
"if",
"startup",
"is",
"not",
"None",
":",
"manager",
"[",
"'server.startup'",
"]",
"=",
"startup",
"if",
"not",
"manager",
".",
"get",
"(",
"'server.startup'",
")",
":",
"# No startup modules, try to load from __main__",
"startup",
"=",
"[",
"]",
"import",
"__main__",
"for",
"k",
"in",
"dir",
"(",
"__main__",
")",
":",
"m",
"=",
"getattr",
"(",
"__main__",
",",
"k",
")",
"if",
"isinstance",
"(",
"m",
",",
"type",
")",
"and",
"issubclass",
"(",
"m",
",",
"Module",
")",
"and",
"m",
"is",
"not",
"Module",
":",
"startup",
".",
"append",
"(",
"'__main__.'",
"+",
"k",
")",
"manager",
"[",
"'server.startup'",
"]",
"=",
"startup",
"if",
"fork",
"is",
"not",
"None",
"and",
"fork",
">",
"1",
":",
"if",
"not",
"hasattr",
"(",
"os",
",",
"'fork'",
")",
":",
"raise",
"ValueError",
"(",
"'Fork is not supported in this operating system.'",
")",
"def",
"start_process",
"(",
")",
":",
"s",
"=",
"Server",
"(",
")",
"s",
".",
"serve",
"(",
")",
"def",
"main_process",
"(",
")",
":",
"if",
"fork",
"is",
"not",
"None",
"and",
"fork",
">",
"1",
":",
"import",
"multiprocessing",
"from",
"time",
"import",
"sleep",
"sub_procs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"fork",
")",
":",
"p",
"=",
"multiprocessing",
".",
"Process",
"(",
"target",
"=",
"start_process",
")",
"sub_procs",
".",
"append",
"(",
"p",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"fork",
")",
":",
"sub_procs",
"[",
"i",
"]",
".",
"start",
"(",
")",
"try",
":",
"import",
"signal",
"def",
"except_return",
"(",
"sig",
",",
"frame",
")",
":",
"raise",
"SystemExit",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"except_return",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"except_return",
")",
"if",
"hasattr",
"(",
"signal",
",",
"'SIGHUP'",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGHUP",
",",
"except_return",
")",
"while",
"True",
":",
"sleep",
"(",
"2",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"fork",
")",
":",
"if",
"sub_procs",
"[",
"i",
"]",
".",
"is_alive",
"(",
")",
":",
"break",
"else",
":",
"break",
"finally",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"fork",
")",
":",
"if",
"sub_procs",
"[",
"i",
"]",
".",
"is_alive",
"(",
")",
":",
"sub_procs",
"[",
"i",
"]",
".",
"terminate",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"fork",
")",
":",
"sub_procs",
"[",
"i",
"]",
".",
"join",
"(",
")",
"else",
":",
"start_process",
"(",
")",
"if",
"daemon",
":",
"import",
"daemon",
"if",
"not",
"pidfile",
":",
"pidfile",
"=",
"manager",
".",
"get",
"(",
"'daemon.pidfile'",
")",
"uid",
"=",
"manager",
".",
"get",
"(",
"'daemon.uid'",
")",
"gid",
"=",
"manager",
".",
"get",
"(",
"'daemon.gid'",
")",
"if",
"gid",
"is",
"None",
":",
"group",
"=",
"manager",
".",
"get",
"(",
"'daemon.group'",
")",
"if",
"group",
"is",
"not",
"None",
":",
"import",
"grp",
"gid",
"=",
"grp",
".",
"getgrnam",
"(",
"group",
")",
"[",
"2",
"]",
"if",
"uid",
"is",
"None",
":",
"import",
"pwd",
"user",
"=",
"manager",
".",
"get",
"(",
"'daemon.user'",
")",
"if",
"user",
"is",
"not",
"None",
":",
"user_pw",
"=",
"pwd",
".",
"getpwnam",
"(",
"user",
")",
"uid",
"=",
"user_pw",
".",
"pw_uid",
"if",
"gid",
"is",
"None",
":",
"gid",
"=",
"user_pw",
".",
"pw_gid",
"if",
"uid",
"is",
"not",
"None",
"and",
"gid",
"is",
"None",
":",
"import",
"pwd",
"gid",
"=",
"pwd",
".",
"getpwuid",
"(",
"uid",
")",
".",
"pw_gid",
"if",
"pidfile",
":",
"import",
"fcntl",
"class",
"PidLocker",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"filepath",
"=",
"path",
"self",
".",
"fd",
"=",
"None",
"def",
"__enter__",
"(",
"self",
")",
":",
"# Create pid file",
"self",
".",
"fd",
"=",
"os",
".",
"open",
"(",
"pidfile",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_TRUNC",
"|",
"os",
".",
"O_CREAT",
",",
"0o644",
")",
"fcntl",
".",
"lockf",
"(",
"self",
".",
"fd",
",",
"fcntl",
".",
"LOCK_EX",
"|",
"fcntl",
".",
"LOCK_NB",
")",
"os",
".",
"write",
"(",
"self",
".",
"fd",
",",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
".",
"encode",
"(",
"'ascii'",
")",
")",
"os",
".",
"fsync",
"(",
"self",
".",
"fd",
")",
"def",
"__exit__",
"(",
"self",
",",
"typ",
",",
"val",
",",
"tb",
")",
":",
"if",
"self",
".",
"fd",
":",
"try",
":",
"fcntl",
".",
"lockf",
"(",
"self",
".",
"fd",
",",
"fcntl",
".",
"LOCK_UN",
")",
"except",
"Exception",
":",
"pass",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")",
"self",
".",
"fd",
"=",
"None",
"locker",
"=",
"PidLocker",
"(",
"pidfile",
")",
"else",
":",
"locker",
"=",
"None",
"import",
"sys",
"# Module loading is related to current path, add it to sys.path",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"cwd",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"cwd",
")",
"# Fix path issues on already-loaded modules",
"for",
"m",
"in",
"sys",
".",
"modules",
".",
"values",
"(",
")",
":",
"if",
"getattr",
"(",
"m",
",",
"'__path__'",
",",
"None",
")",
":",
"m",
".",
"__path__",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"p",
")",
"for",
"p",
"in",
"m",
".",
"__path__",
"]",
"# __file__ is used for module-relative resource locate",
"if",
"getattr",
"(",
"m",
",",
"'__file__'",
",",
"None",
")",
":",
"m",
".",
"__file__",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"m",
".",
"__file__",
")",
"configs",
"=",
"{",
"'gid'",
":",
"gid",
",",
"'uid'",
":",
"uid",
",",
"'pidfile'",
":",
"locker",
"}",
"config_filters",
"=",
"[",
"'chroot_directory'",
",",
"'working_directory'",
",",
"'umask'",
",",
"'detach_process'",
",",
"'prevent_core'",
"]",
"if",
"hasattr",
"(",
"manager",
",",
"'daemon'",
")",
":",
"configs",
".",
"update",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"manager",
".",
"daemon",
".",
"config_value_items",
"(",
")",
"if",
"k",
"in",
"config_filters",
")",
"if",
"not",
"hasattr",
"(",
"os",
",",
"'initgroups'",
")",
":",
"configs",
"[",
"'initgroups'",
"]",
"=",
"False",
"with",
"daemon",
".",
"DaemonContext",
"(",
"*",
"*",
"configs",
")",
":",
"main_process",
"(",
")",
"else",
":",
"main_process",
"(",
")"
] | The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
is used; if `server.startup` is not configured, any module defined or imported
into __main__ is loaded.
:param daemon: if True, use python-daemon to fork and start at background. `python-daemon` must be
installed::
pip install python-daemon
:param pidfile: if daemon=True, this file is used for the pidfile.
:param fork: use extra fork to start multiple instances | [
"The",
"most",
"simple",
"way",
"to",
"start",
"the",
"VLCP",
"framework",
":",
"param",
"configpath",
":",
"path",
"of",
"a",
"configuration",
"file",
"to",
"be",
"loaded",
":",
"param",
"startup",
":",
"startup",
"modules",
"list",
".",
"If",
"None",
"server",
".",
"startup",
"in",
"the",
"configuration",
"files",
"is",
"used",
";",
"if",
"server",
".",
"startup",
"is",
"not",
"configured",
"any",
"module",
"defined",
"or",
"imported",
"into",
"__main__",
"is",
"loaded",
".",
":",
"param",
"daemon",
":",
"if",
"True",
"use",
"python",
"-",
"daemon",
"to",
"fork",
"and",
"start",
"at",
"background",
".",
"python",
"-",
"daemon",
"must",
"be",
"installed",
"::",
"pip",
"install",
"python",
"-",
"daemon",
":",
"param",
"pidfile",
":",
"if",
"daemon",
"=",
"True",
"this",
"file",
"is",
"used",
"for",
"the",
"pidfile",
".",
":",
"param",
"fork",
":",
"use",
"extra",
"fork",
"to",
"start",
"multiple",
"instances"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/server.py#L174-L312 |
hubo1016/vlcp | vlcp/service/sdn/vxlancast.py | VXLANUpdater.wait_for_group | async def wait_for_group(self, container, networkid, timeout = 120):
"""
Wait for a VXLAN group to be created
"""
if networkid in self._current_groups:
return self._current_groups[networkid]
else:
if not self._connection.connected:
raise ConnectionResetException
groupchanged = VXLANGroupChanged.createMatcher(self._connection, networkid, VXLANGroupChanged.UPDATED)
conn_down = self._connection.protocol.statematcher(self._connection)
timeout_, ev, m = await container.wait_with_timeout(timeout, groupchanged, conn_down)
if timeout_:
raise ValueError('VXLAN group is still not created after a long time')
elif m is conn_down:
raise ConnectionResetException
else:
return ev.physicalportid | python | async def wait_for_group(self, container, networkid, timeout = 120):
"""
Wait for a VXLAN group to be created
"""
if networkid in self._current_groups:
return self._current_groups[networkid]
else:
if not self._connection.connected:
raise ConnectionResetException
groupchanged = VXLANGroupChanged.createMatcher(self._connection, networkid, VXLANGroupChanged.UPDATED)
conn_down = self._connection.protocol.statematcher(self._connection)
timeout_, ev, m = await container.wait_with_timeout(timeout, groupchanged, conn_down)
if timeout_:
raise ValueError('VXLAN group is still not created after a long time')
elif m is conn_down:
raise ConnectionResetException
else:
return ev.physicalportid | [
"async",
"def",
"wait_for_group",
"(",
"self",
",",
"container",
",",
"networkid",
",",
"timeout",
"=",
"120",
")",
":",
"if",
"networkid",
"in",
"self",
".",
"_current_groups",
":",
"return",
"self",
".",
"_current_groups",
"[",
"networkid",
"]",
"else",
":",
"if",
"not",
"self",
".",
"_connection",
".",
"connected",
":",
"raise",
"ConnectionResetException",
"groupchanged",
"=",
"VXLANGroupChanged",
".",
"createMatcher",
"(",
"self",
".",
"_connection",
",",
"networkid",
",",
"VXLANGroupChanged",
".",
"UPDATED",
")",
"conn_down",
"=",
"self",
".",
"_connection",
".",
"protocol",
".",
"statematcher",
"(",
"self",
".",
"_connection",
")",
"timeout_",
",",
"ev",
",",
"m",
"=",
"await",
"container",
".",
"wait_with_timeout",
"(",
"timeout",
",",
"groupchanged",
",",
"conn_down",
")",
"if",
"timeout_",
":",
"raise",
"ValueError",
"(",
"'VXLAN group is still not created after a long time'",
")",
"elif",
"m",
"is",
"conn_down",
":",
"raise",
"ConnectionResetException",
"else",
":",
"return",
"ev",
".",
"physicalportid"
] | Wait for a VXLAN group to be created | [
"Wait",
"for",
"a",
"VXLAN",
"group",
"to",
"be",
"created"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/service/sdn/vxlancast.py#L80-L97 |
hubo1016/vlcp | vlcp/event/stream.py | BaseStream.read | async def read(self, container = None, size = None):
"""
Coroutine method to read from the stream and return the data. Raises EOFError
when the stream end has been reached; raises IOError if there are other errors.
:param container: A routine container
:param size: maximum read size, or unlimited if is None
"""
ret = []
retsize = 0
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
while size is None or retsize < size:
if self.pos >= len(self.data):
await self.prepareRead(container)
if size is None or size - retsize >= len(self.data) - self.pos:
t = self.data[self.pos:]
ret.append(t)
retsize += len(t)
self.pos = len(self.data)
if self.dataeof:
self.eof = True
break
if self.dataerror:
self.errored = True
break
else:
ret.append(self.data[self.pos:self.pos + (size - retsize)])
self.pos += (size - retsize)
retsize = size
break
if self.isunicode:
return u''.join(ret)
else:
return b''.join(ret)
if self.errored:
raise IOError('Stream is broken before EOF') | python | async def read(self, container = None, size = None):
"""
Coroutine method to read from the stream and return the data. Raises EOFError
when the stream end has been reached; raises IOError if there are other errors.
:param container: A routine container
:param size: maximum read size, or unlimited if is None
"""
ret = []
retsize = 0
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
while size is None or retsize < size:
if self.pos >= len(self.data):
await self.prepareRead(container)
if size is None or size - retsize >= len(self.data) - self.pos:
t = self.data[self.pos:]
ret.append(t)
retsize += len(t)
self.pos = len(self.data)
if self.dataeof:
self.eof = True
break
if self.dataerror:
self.errored = True
break
else:
ret.append(self.data[self.pos:self.pos + (size - retsize)])
self.pos += (size - retsize)
retsize = size
break
if self.isunicode:
return u''.join(ret)
else:
return b''.join(ret)
if self.errored:
raise IOError('Stream is broken before EOF') | [
"async",
"def",
"read",
"(",
"self",
",",
"container",
"=",
"None",
",",
"size",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"retsize",
"=",
"0",
"if",
"self",
".",
"eof",
":",
"raise",
"EOFError",
"if",
"self",
".",
"errored",
":",
"raise",
"IOError",
"(",
"'Stream is broken before EOF'",
")",
"while",
"size",
"is",
"None",
"or",
"retsize",
"<",
"size",
":",
"if",
"self",
".",
"pos",
">=",
"len",
"(",
"self",
".",
"data",
")",
":",
"await",
"self",
".",
"prepareRead",
"(",
"container",
")",
"if",
"size",
"is",
"None",
"or",
"size",
"-",
"retsize",
">=",
"len",
"(",
"self",
".",
"data",
")",
"-",
"self",
".",
"pos",
":",
"t",
"=",
"self",
".",
"data",
"[",
"self",
".",
"pos",
":",
"]",
"ret",
".",
"append",
"(",
"t",
")",
"retsize",
"+=",
"len",
"(",
"t",
")",
"self",
".",
"pos",
"=",
"len",
"(",
"self",
".",
"data",
")",
"if",
"self",
".",
"dataeof",
":",
"self",
".",
"eof",
"=",
"True",
"break",
"if",
"self",
".",
"dataerror",
":",
"self",
".",
"errored",
"=",
"True",
"break",
"else",
":",
"ret",
".",
"append",
"(",
"self",
".",
"data",
"[",
"self",
".",
"pos",
":",
"self",
".",
"pos",
"+",
"(",
"size",
"-",
"retsize",
")",
"]",
")",
"self",
".",
"pos",
"+=",
"(",
"size",
"-",
"retsize",
")",
"retsize",
"=",
"size",
"break",
"if",
"self",
".",
"isunicode",
":",
"return",
"u''",
".",
"join",
"(",
"ret",
")",
"else",
":",
"return",
"b''",
".",
"join",
"(",
"ret",
")",
"if",
"self",
".",
"errored",
":",
"raise",
"IOError",
"(",
"'Stream is broken before EOF'",
")"
] | Coroutine method to read from the stream and return the data. Raises EOFError
when the stream end has been reached; raises IOError if there are other errors.
:param container: A routine container
:param size: maximum read size, or unlimited if is None | [
"Coroutine",
"method",
"to",
"read",
"from",
"the",
"stream",
"and",
"return",
"the",
"data",
".",
"Raises",
"EOFError",
"when",
"the",
"stream",
"end",
"has",
"been",
"reached",
";",
"raises",
"IOError",
"if",
"there",
"are",
"other",
"errors",
".",
":",
"param",
"container",
":",
"A",
"routine",
"container",
":",
"param",
"size",
":",
"maximum",
"read",
"size",
"or",
"unlimited",
"if",
"is",
"None"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/stream.py#L58-L97 |
hubo1016/vlcp | vlcp/event/stream.py | BaseStream.readonce | def readonce(self, size = None):
"""
Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
to read the next chunk of data.
This is not a coroutine method.
"""
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
if size is not None and size < len(self.data) - self.pos:
ret = self.data[self.pos: self.pos + size]
self.pos += size
return ret
else:
ret = self.data[self.pos:]
self.pos = len(self.data)
if self.dataeof:
self.eof = True
return ret | python | def readonce(self, size = None):
"""
Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
to read the next chunk of data.
This is not a coroutine method.
"""
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
if size is not None and size < len(self.data) - self.pos:
ret = self.data[self.pos: self.pos + size]
self.pos += size
return ret
else:
ret = self.data[self.pos:]
self.pos = len(self.data)
if self.dataeof:
self.eof = True
return ret | [
"def",
"readonce",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"eof",
":",
"raise",
"EOFError",
"if",
"self",
".",
"errored",
":",
"raise",
"IOError",
"(",
"'Stream is broken before EOF'",
")",
"if",
"size",
"is",
"not",
"None",
"and",
"size",
"<",
"len",
"(",
"self",
".",
"data",
")",
"-",
"self",
".",
"pos",
":",
"ret",
"=",
"self",
".",
"data",
"[",
"self",
".",
"pos",
":",
"self",
".",
"pos",
"+",
"size",
"]",
"self",
".",
"pos",
"+=",
"size",
"return",
"ret",
"else",
":",
"ret",
"=",
"self",
".",
"data",
"[",
"self",
".",
"pos",
":",
"]",
"self",
".",
"pos",
"=",
"len",
"(",
"self",
".",
"data",
")",
"if",
"self",
".",
"dataeof",
":",
"self",
".",
"eof",
"=",
"True",
"return",
"ret"
] | Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
to read the next chunk of data.
This is not a coroutine method. | [
"Read",
"from",
"current",
"buffer",
".",
"If",
"current",
"buffer",
"is",
"empty",
"returns",
"an",
"empty",
"string",
".",
"You",
"can",
"use",
"prepareRead",
"to",
"read",
"the",
"next",
"chunk",
"of",
"data",
".",
"This",
"is",
"not",
"a",
"coroutine",
"method",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/stream.py#L98-L118 |
hubo1016/vlcp | vlcp/event/stream.py | BaseStream.readline | async def readline(self, container = None, size = None):
"""
Coroutine method which reads the next line or until EOF or size exceeds
"""
ret = []
retsize = 0
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
while size is None or retsize < size:
if self.pos >= len(self.data):
await self.prepareRead(container)
if size is None or size - retsize >= len(self.data) - self.pos:
t = self.data[self.pos:]
if self.isunicode:
p = t.find(u'\n')
else:
p = t.find(b'\n')
if p >= 0:
t = t[0: p + 1]
ret.append(t)
retsize += len(t)
self.pos += len(t)
break
else:
ret.append(t)
retsize += len(t)
self.pos += len(t)
if self.dataeof:
self.eof = True
break
if self.dataerror:
self.errored = True
break
else:
t = self.data[self.pos:self.pos + (size - retsize)]
if self.isunicode:
p = t.find(u'\n')
else:
p = t.find(b'\n')
if p >= 0:
t = t[0: p + 1]
ret.append(t)
self.pos += len(t)
retsize += len(t)
break
if self.isunicode:
return u''.join(ret)
else:
return b''.join(ret)
if self.errored:
raise IOError('Stream is broken before EOF') | python | async def readline(self, container = None, size = None):
"""
Coroutine method which reads the next line or until EOF or size exceeds
"""
ret = []
retsize = 0
if self.eof:
raise EOFError
if self.errored:
raise IOError('Stream is broken before EOF')
while size is None or retsize < size:
if self.pos >= len(self.data):
await self.prepareRead(container)
if size is None or size - retsize >= len(self.data) - self.pos:
t = self.data[self.pos:]
if self.isunicode:
p = t.find(u'\n')
else:
p = t.find(b'\n')
if p >= 0:
t = t[0: p + 1]
ret.append(t)
retsize += len(t)
self.pos += len(t)
break
else:
ret.append(t)
retsize += len(t)
self.pos += len(t)
if self.dataeof:
self.eof = True
break
if self.dataerror:
self.errored = True
break
else:
t = self.data[self.pos:self.pos + (size - retsize)]
if self.isunicode:
p = t.find(u'\n')
else:
p = t.find(b'\n')
if p >= 0:
t = t[0: p + 1]
ret.append(t)
self.pos += len(t)
retsize += len(t)
break
if self.isunicode:
return u''.join(ret)
else:
return b''.join(ret)
if self.errored:
raise IOError('Stream is broken before EOF') | [
"async",
"def",
"readline",
"(",
"self",
",",
"container",
"=",
"None",
",",
"size",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"retsize",
"=",
"0",
"if",
"self",
".",
"eof",
":",
"raise",
"EOFError",
"if",
"self",
".",
"errored",
":",
"raise",
"IOError",
"(",
"'Stream is broken before EOF'",
")",
"while",
"size",
"is",
"None",
"or",
"retsize",
"<",
"size",
":",
"if",
"self",
".",
"pos",
">=",
"len",
"(",
"self",
".",
"data",
")",
":",
"await",
"self",
".",
"prepareRead",
"(",
"container",
")",
"if",
"size",
"is",
"None",
"or",
"size",
"-",
"retsize",
">=",
"len",
"(",
"self",
".",
"data",
")",
"-",
"self",
".",
"pos",
":",
"t",
"=",
"self",
".",
"data",
"[",
"self",
".",
"pos",
":",
"]",
"if",
"self",
".",
"isunicode",
":",
"p",
"=",
"t",
".",
"find",
"(",
"u'\\n'",
")",
"else",
":",
"p",
"=",
"t",
".",
"find",
"(",
"b'\\n'",
")",
"if",
"p",
">=",
"0",
":",
"t",
"=",
"t",
"[",
"0",
":",
"p",
"+",
"1",
"]",
"ret",
".",
"append",
"(",
"t",
")",
"retsize",
"+=",
"len",
"(",
"t",
")",
"self",
".",
"pos",
"+=",
"len",
"(",
"t",
")",
"break",
"else",
":",
"ret",
".",
"append",
"(",
"t",
")",
"retsize",
"+=",
"len",
"(",
"t",
")",
"self",
".",
"pos",
"+=",
"len",
"(",
"t",
")",
"if",
"self",
".",
"dataeof",
":",
"self",
".",
"eof",
"=",
"True",
"break",
"if",
"self",
".",
"dataerror",
":",
"self",
".",
"errored",
"=",
"True",
"break",
"else",
":",
"t",
"=",
"self",
".",
"data",
"[",
"self",
".",
"pos",
":",
"self",
".",
"pos",
"+",
"(",
"size",
"-",
"retsize",
")",
"]",
"if",
"self",
".",
"isunicode",
":",
"p",
"=",
"t",
".",
"find",
"(",
"u'\\n'",
")",
"else",
":",
"p",
"=",
"t",
".",
"find",
"(",
"b'\\n'",
")",
"if",
"p",
">=",
"0",
":",
"t",
"=",
"t",
"[",
"0",
":",
"p",
"+",
"1",
"]",
"ret",
".",
"append",
"(",
"t",
")",
"self",
".",
"pos",
"+=",
"len",
"(",
"t",
")",
"retsize",
"+=",
"len",
"(",
"t",
")",
"break",
"if",
"self",
".",
"isunicode",
":",
"return",
"u''",
".",
"join",
"(",
"ret",
")",
"else",
":",
"return",
"b''",
".",
"join",
"(",
"ret",
")",
"if",
"self",
".",
"errored",
":",
"raise",
"IOError",
"(",
"'Stream is broken before EOF'",
")"
] | Coroutine method which reads the next line or until EOF or size exceeds | [
"Coroutine",
"method",
"which",
"reads",
"the",
"next",
"line",
"or",
"until",
"EOF",
"or",
"size",
"exceeds"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/stream.py#L125-L177 |
hubo1016/vlcp | vlcp/event/stream.py | BaseStream.copy_to | async def copy_to(self, dest, container, buffering = True):
"""
Coroutine method to copy content from this stream to another stream.
"""
if self.eof:
await dest.write(u'' if self.isunicode else b'', True)
elif self.errored:
await dest.error(container)
else:
try:
while not self.eof:
await self.prepareRead(container)
data = self.readonce()
try:
await dest.write(data, container, self.eof, buffering = buffering)
except IOError:
break
except:
async def _cleanup():
try:
await dest.error(container)
except IOError:
pass
container.subroutine(_cleanup(), False)
raise
finally:
self.close(container.scheduler) | python | async def copy_to(self, dest, container, buffering = True):
"""
Coroutine method to copy content from this stream to another stream.
"""
if self.eof:
await dest.write(u'' if self.isunicode else b'', True)
elif self.errored:
await dest.error(container)
else:
try:
while not self.eof:
await self.prepareRead(container)
data = self.readonce()
try:
await dest.write(data, container, self.eof, buffering = buffering)
except IOError:
break
except:
async def _cleanup():
try:
await dest.error(container)
except IOError:
pass
container.subroutine(_cleanup(), False)
raise
finally:
self.close(container.scheduler) | [
"async",
"def",
"copy_to",
"(",
"self",
",",
"dest",
",",
"container",
",",
"buffering",
"=",
"True",
")",
":",
"if",
"self",
".",
"eof",
":",
"await",
"dest",
".",
"write",
"(",
"u''",
"if",
"self",
".",
"isunicode",
"else",
"b''",
",",
"True",
")",
"elif",
"self",
".",
"errored",
":",
"await",
"dest",
".",
"error",
"(",
"container",
")",
"else",
":",
"try",
":",
"while",
"not",
"self",
".",
"eof",
":",
"await",
"self",
".",
"prepareRead",
"(",
"container",
")",
"data",
"=",
"self",
".",
"readonce",
"(",
")",
"try",
":",
"await",
"dest",
".",
"write",
"(",
"data",
",",
"container",
",",
"self",
".",
"eof",
",",
"buffering",
"=",
"buffering",
")",
"except",
"IOError",
":",
"break",
"except",
":",
"async",
"def",
"_cleanup",
"(",
")",
":",
"try",
":",
"await",
"dest",
".",
"error",
"(",
"container",
")",
"except",
"IOError",
":",
"pass",
"container",
".",
"subroutine",
"(",
"_cleanup",
"(",
")",
",",
"False",
")",
"raise",
"finally",
":",
"self",
".",
"close",
"(",
"container",
".",
"scheduler",
")"
] | Coroutine method to copy content from this stream to another stream. | [
"Coroutine",
"method",
"to",
"copy",
"content",
"from",
"this",
"stream",
"to",
"another",
"stream",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/stream.py#L178-L204 |
hubo1016/vlcp | vlcp/event/stream.py | BaseStream.write | async def write(self, data, container, eof = False, ignoreexception = False, buffering = True, split = True):
"""
Coroutine method to write data to this stream.
:param data: data to write
:param container: the routine container
:param eof: if True, this is the last chunk of this stream. The other end will receive an EOF after reading
this chunk.
:param ignoreexception: even if the stream is closed on the other side, do not raise exception.
:param buffering: enable buffering. The written data may not be sent if buffering = True; if buffering = False,
immediately send any data in the buffer together with this chunk.
:param split: enable splitting. If this chunk is too large, the stream is allowed to split it into
smaller chunks for better balancing.
"""
if not ignoreexception:
raise IOError('Stream is closed') | python | async def write(self, data, container, eof = False, ignoreexception = False, buffering = True, split = True):
"""
Coroutine method to write data to this stream.
:param data: data to write
:param container: the routine container
:param eof: if True, this is the last chunk of this stream. The other end will receive an EOF after reading
this chunk.
:param ignoreexception: even if the stream is closed on the other side, do not raise exception.
:param buffering: enable buffering. The written data may not be sent if buffering = True; if buffering = False,
immediately send any data in the buffer together with this chunk.
:param split: enable splitting. If this chunk is too large, the stream is allowed to split it into
smaller chunks for better balancing.
"""
if not ignoreexception:
raise IOError('Stream is closed') | [
"async",
"def",
"write",
"(",
"self",
",",
"data",
",",
"container",
",",
"eof",
"=",
"False",
",",
"ignoreexception",
"=",
"False",
",",
"buffering",
"=",
"True",
",",
"split",
"=",
"True",
")",
":",
"if",
"not",
"ignoreexception",
":",
"raise",
"IOError",
"(",
"'Stream is closed'",
")"
] | Coroutine method to write data to this stream.
:param data: data to write
:param container: the routine container
:param eof: if True, this is the last chunk of this stream. The other end will receive an EOF after reading
this chunk.
:param ignoreexception: even if the stream is closed on the other side, do not raise exception.
:param buffering: enable buffering. The written data may not be sent if buffering = True; if buffering = False,
immediately send any data in the buffer together with this chunk.
:param split: enable splitting. If this chunk is too large, the stream is allowed to split it into
smaller chunks for better balancing. | [
"Coroutine",
"method",
"to",
"write",
"data",
"to",
"this",
"stream",
".",
":",
"param",
"data",
":",
"data",
"to",
"write",
":",
"param",
"container",
":",
"the",
"routine",
"container",
":",
"param",
"eof",
":",
"if",
"True",
"this",
"is",
"the",
"last",
"chunk",
"of",
"this",
"stream",
".",
"The",
"other",
"end",
"will",
"receive",
"an",
"EOF",
"after",
"reading",
"this",
"chunk",
".",
":",
"param",
"ignoreexception",
":",
"even",
"if",
"the",
"stream",
"is",
"closed",
"on",
"the",
"other",
"side",
"do",
"not",
"raise",
"exception",
".",
":",
"param",
"buffering",
":",
"enable",
"buffering",
".",
"The",
"written",
"data",
"may",
"not",
"be",
"sent",
"if",
"buffering",
"=",
"True",
";",
"if",
"buffering",
"=",
"False",
"immediately",
"send",
"any",
"data",
"in",
"the",
"buffer",
"together",
"with",
"this",
"chunk",
".",
":",
"param",
"split",
":",
"enable",
"splitting",
".",
"If",
"this",
"chunk",
"is",
"too",
"large",
"the",
"stream",
"is",
"allowed",
"to",
"split",
"it",
"into",
"smaller",
"chunks",
"for",
"better",
"balancing",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/stream.py#L208-L228 |
hubo1016/vlcp | vlcp/event/matchtree.py | MatchTree.subtree | def subtree(self, matcher, create = False):
'''
Find a subtree from a matcher
:param matcher: the matcher to locate the subtree. If None, return the root of the tree.
:param create: if True, the subtree is created if not exists; otherwise return None if not exists
'''
if matcher is None:
return self
current = self
for i in range(self.depth, len(matcher.indices)):
ind = matcher.indices[i]
if ind is None:
# match Any
if hasattr(current, 'any'):
current = current.any
else:
if create:
cany = MatchTree(current)
cany.parentIndex = None
current.any = cany
current = cany
else:
return None
else:
current2 = current.index.get(ind)
if current2 is None:
if create:
cind = MatchTree(current)
cind.parentIndex = ind
current.index[ind] = cind
current = cind
else:
return None
else:
current = current2
return current | python | def subtree(self, matcher, create = False):
'''
Find a subtree from a matcher
:param matcher: the matcher to locate the subtree. If None, return the root of the tree.
:param create: if True, the subtree is created if not exists; otherwise return None if not exists
'''
if matcher is None:
return self
current = self
for i in range(self.depth, len(matcher.indices)):
ind = matcher.indices[i]
if ind is None:
# match Any
if hasattr(current, 'any'):
current = current.any
else:
if create:
cany = MatchTree(current)
cany.parentIndex = None
current.any = cany
current = cany
else:
return None
else:
current2 = current.index.get(ind)
if current2 is None:
if create:
cind = MatchTree(current)
cind.parentIndex = ind
current.index[ind] = cind
current = cind
else:
return None
else:
current = current2
return current | [
"def",
"subtree",
"(",
"self",
",",
"matcher",
",",
"create",
"=",
"False",
")",
":",
"if",
"matcher",
"is",
"None",
":",
"return",
"self",
"current",
"=",
"self",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"depth",
",",
"len",
"(",
"matcher",
".",
"indices",
")",
")",
":",
"ind",
"=",
"matcher",
".",
"indices",
"[",
"i",
"]",
"if",
"ind",
"is",
"None",
":",
"# match Any",
"if",
"hasattr",
"(",
"current",
",",
"'any'",
")",
":",
"current",
"=",
"current",
".",
"any",
"else",
":",
"if",
"create",
":",
"cany",
"=",
"MatchTree",
"(",
"current",
")",
"cany",
".",
"parentIndex",
"=",
"None",
"current",
".",
"any",
"=",
"cany",
"current",
"=",
"cany",
"else",
":",
"return",
"None",
"else",
":",
"current2",
"=",
"current",
".",
"index",
".",
"get",
"(",
"ind",
")",
"if",
"current2",
"is",
"None",
":",
"if",
"create",
":",
"cind",
"=",
"MatchTree",
"(",
"current",
")",
"cind",
".",
"parentIndex",
"=",
"ind",
"current",
".",
"index",
"[",
"ind",
"]",
"=",
"cind",
"current",
"=",
"cind",
"else",
":",
"return",
"None",
"else",
":",
"current",
"=",
"current2",
"return",
"current"
] | Find a subtree from a matcher
:param matcher: the matcher to locate the subtree. If None, return the root of the tree.
:param create: if True, the subtree is created if not exists; otherwise return None if not exists | [
"Find",
"a",
"subtree",
"from",
"a",
"matcher",
":",
"param",
"matcher",
":",
"the",
"matcher",
"to",
"locate",
"the",
"subtree",
".",
"If",
"None",
"return",
"the",
"root",
"of",
"the",
"tree",
".",
":",
"param",
"create",
":",
"if",
"True",
"the",
"subtree",
"is",
"created",
"if",
"not",
"exists",
";",
"otherwise",
"return",
"None",
"if",
"not",
"exists"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L29-L66 |
hubo1016/vlcp | vlcp/event/matchtree.py | MatchTree.insert | def insert(self, matcher, obj):
'''
Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return
'''
current = self.subtree(matcher, True)
#current.matchers[(obj, matcher)] = None
if current._use_dict:
current.matchers_dict[(obj, matcher)] = None
else:
current.matchers_list.append((obj, matcher))
return current | python | def insert(self, matcher, obj):
'''
Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return
'''
current = self.subtree(matcher, True)
#current.matchers[(obj, matcher)] = None
if current._use_dict:
current.matchers_dict[(obj, matcher)] = None
else:
current.matchers_list.append((obj, matcher))
return current | [
"def",
"insert",
"(",
"self",
",",
"matcher",
",",
"obj",
")",
":",
"current",
"=",
"self",
".",
"subtree",
"(",
"matcher",
",",
"True",
")",
"#current.matchers[(obj, matcher)] = None",
"if",
"current",
".",
"_use_dict",
":",
"current",
".",
"matchers_dict",
"[",
"(",
"obj",
",",
"matcher",
")",
"]",
"=",
"None",
"else",
":",
"current",
".",
"matchers_list",
".",
"append",
"(",
"(",
"obj",
",",
"matcher",
")",
")",
"return",
"current"
] | Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return | [
"Insert",
"a",
"new",
"matcher",
":",
"param",
"matcher",
":",
"an",
"EventMatcher",
":",
"param",
"obj",
":",
"object",
"to",
"return"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L67-L81 |
hubo1016/vlcp | vlcp/event/matchtree.py | MatchTree.remove | def remove(self, matcher, obj):
'''
Remove the matcher
:param matcher: an EventMatcher
:param obj: the object to remove
'''
current = self.subtree(matcher, False)
if current is None:
return
# Assume that this pair only appears once
if current._use_dict:
try:
del current.matchers_dict[(obj, matcher)]
except KeyError:
pass
else:
if len(current.matchers_list) > 10:
# Convert to dict
current.matchers_dict = OrderedDict((v, None) for v in current.matchers_list
if v != (obj, matcher))
current.matchers_list = None
current._use_dict = True
else:
try:
current.matchers_list.remove((obj, matcher))
except ValueError:
pass
while ((not current.matchers_dict) if current._use_dict
else (not current.matchers_list))\
and not current.matchers_dict\
and not hasattr(current,'any')\
and not current.index and current.parent is not None:
# remove self from parents
ind = current.parentIndex
if ind is None:
del current.parent.any
else:
del current.parent.index[ind]
p = current.parent
current.parent = None
current = p | python | def remove(self, matcher, obj):
'''
Remove the matcher
:param matcher: an EventMatcher
:param obj: the object to remove
'''
current = self.subtree(matcher, False)
if current is None:
return
# Assume that this pair only appears once
if current._use_dict:
try:
del current.matchers_dict[(obj, matcher)]
except KeyError:
pass
else:
if len(current.matchers_list) > 10:
# Convert to dict
current.matchers_dict = OrderedDict((v, None) for v in current.matchers_list
if v != (obj, matcher))
current.matchers_list = None
current._use_dict = True
else:
try:
current.matchers_list.remove((obj, matcher))
except ValueError:
pass
while ((not current.matchers_dict) if current._use_dict
else (not current.matchers_list))\
and not current.matchers_dict\
and not hasattr(current,'any')\
and not current.index and current.parent is not None:
# remove self from parents
ind = current.parentIndex
if ind is None:
del current.parent.any
else:
del current.parent.index[ind]
p = current.parent
current.parent = None
current = p | [
"def",
"remove",
"(",
"self",
",",
"matcher",
",",
"obj",
")",
":",
"current",
"=",
"self",
".",
"subtree",
"(",
"matcher",
",",
"False",
")",
"if",
"current",
"is",
"None",
":",
"return",
"# Assume that this pair only appears once",
"if",
"current",
".",
"_use_dict",
":",
"try",
":",
"del",
"current",
".",
"matchers_dict",
"[",
"(",
"obj",
",",
"matcher",
")",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"len",
"(",
"current",
".",
"matchers_list",
")",
">",
"10",
":",
"# Convert to dict",
"current",
".",
"matchers_dict",
"=",
"OrderedDict",
"(",
"(",
"v",
",",
"None",
")",
"for",
"v",
"in",
"current",
".",
"matchers_list",
"if",
"v",
"!=",
"(",
"obj",
",",
"matcher",
")",
")",
"current",
".",
"matchers_list",
"=",
"None",
"current",
".",
"_use_dict",
"=",
"True",
"else",
":",
"try",
":",
"current",
".",
"matchers_list",
".",
"remove",
"(",
"(",
"obj",
",",
"matcher",
")",
")",
"except",
"ValueError",
":",
"pass",
"while",
"(",
"(",
"not",
"current",
".",
"matchers_dict",
")",
"if",
"current",
".",
"_use_dict",
"else",
"(",
"not",
"current",
".",
"matchers_list",
")",
")",
"and",
"not",
"current",
".",
"matchers_dict",
"and",
"not",
"hasattr",
"(",
"current",
",",
"'any'",
")",
"and",
"not",
"current",
".",
"index",
"and",
"current",
".",
"parent",
"is",
"not",
"None",
":",
"# remove self from parents",
"ind",
"=",
"current",
".",
"parentIndex",
"if",
"ind",
"is",
"None",
":",
"del",
"current",
".",
"parent",
".",
"any",
"else",
":",
"del",
"current",
".",
"parent",
".",
"index",
"[",
"ind",
"]",
"p",
"=",
"current",
".",
"parent",
"current",
".",
"parent",
"=",
"None",
"current",
"=",
"p"
] | Remove the matcher
:param matcher: an EventMatcher
:param obj: the object to remove | [
"Remove",
"the",
"matcher",
":",
"param",
"matcher",
":",
"an",
"EventMatcher",
":",
"param",
"obj",
":",
"the",
"object",
"to",
"remove"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L82-L124 |
hubo1016/vlcp | vlcp/event/matchtree.py | MatchTree.matchesWithMatchers | def matchesWithMatchers(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
'''
ret = []
self._matches(event, set(), ret)
return tuple(ret) | python | def matchesWithMatchers(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
'''
ret = []
self._matches(event, set(), ret)
return tuple(ret) | [
"def",
"matchesWithMatchers",
"(",
"self",
",",
"event",
")",
":",
"ret",
"=",
"[",
"]",
"self",
".",
"_matches",
"(",
"event",
",",
"set",
"(",
")",
",",
"ret",
")",
"return",
"tuple",
"(",
"ret",
")"
] | Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event | [
"Return",
"all",
"matches",
"for",
"this",
"event",
".",
"The",
"first",
"matcher",
"is",
"also",
"returned",
"for",
"each",
"matched",
"object",
".",
":",
"param",
"event",
":",
"an",
"input",
"event"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L125-L133 |
hubo1016/vlcp | vlcp/event/matchtree.py | MatchTree.matches | def matches(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
'''
ret = []
self._matches(event, set(), ret)
return tuple(r[0] for r in ret) | python | def matches(self, event):
'''
Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event
'''
ret = []
self._matches(event, set(), ret)
return tuple(r[0] for r in ret) | [
"def",
"matches",
"(",
"self",
",",
"event",
")",
":",
"ret",
"=",
"[",
"]",
"self",
".",
"_matches",
"(",
"event",
",",
"set",
"(",
")",
",",
"ret",
")",
"return",
"tuple",
"(",
"r",
"[",
"0",
"]",
"for",
"r",
"in",
"ret",
")"
] | Return all matches for this event. The first matcher is also returned for each matched object.
:param event: an input event | [
"Return",
"all",
"matches",
"for",
"this",
"event",
".",
"The",
"first",
"matcher",
"is",
"also",
"returned",
"for",
"each",
"matched",
"object",
".",
":",
"param",
"event",
":",
"an",
"input",
"event"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L134-L142 |
hubo1016/vlcp | vlcp/event/matchtree.py | MatchTree.matchfirst | def matchfirst(self, event):
'''
Return first match for this event
:param event: an input event
'''
# 1. matches(self.index[ind], event)
# 2. matches(self.any, event)
# 3. self.matches
if self.depth < len(event.indices):
ind = event.indices[self.depth]
if ind in self.index:
m = self.index[ind].matchfirst(event)
if m is not None:
return m
if hasattr(self, 'any'):
m = self.any.matchfirst(event)
if m is not None:
return m
if self._use_dict:
for o, m in self.matchers_dict:
if m is None or m.judge(event):
return o
else:
for o, m in self.matchers_list:
if m is None or m.judge(event):
return o | python | def matchfirst(self, event):
'''
Return first match for this event
:param event: an input event
'''
# 1. matches(self.index[ind], event)
# 2. matches(self.any, event)
# 3. self.matches
if self.depth < len(event.indices):
ind = event.indices[self.depth]
if ind in self.index:
m = self.index[ind].matchfirst(event)
if m is not None:
return m
if hasattr(self, 'any'):
m = self.any.matchfirst(event)
if m is not None:
return m
if self._use_dict:
for o, m in self.matchers_dict:
if m is None or m.judge(event):
return o
else:
for o, m in self.matchers_list:
if m is None or m.judge(event):
return o | [
"def",
"matchfirst",
"(",
"self",
",",
"event",
")",
":",
"# 1. matches(self.index[ind], event)",
"# 2. matches(self.any, event)",
"# 3. self.matches",
"if",
"self",
".",
"depth",
"<",
"len",
"(",
"event",
".",
"indices",
")",
":",
"ind",
"=",
"event",
".",
"indices",
"[",
"self",
".",
"depth",
"]",
"if",
"ind",
"in",
"self",
".",
"index",
":",
"m",
"=",
"self",
".",
"index",
"[",
"ind",
"]",
".",
"matchfirst",
"(",
"event",
")",
"if",
"m",
"is",
"not",
"None",
":",
"return",
"m",
"if",
"hasattr",
"(",
"self",
",",
"'any'",
")",
":",
"m",
"=",
"self",
".",
"any",
".",
"matchfirst",
"(",
"event",
")",
"if",
"m",
"is",
"not",
"None",
":",
"return",
"m",
"if",
"self",
".",
"_use_dict",
":",
"for",
"o",
",",
"m",
"in",
"self",
".",
"matchers_dict",
":",
"if",
"m",
"is",
"None",
"or",
"m",
".",
"judge",
"(",
"event",
")",
":",
"return",
"o",
"else",
":",
"for",
"o",
",",
"m",
"in",
"self",
".",
"matchers_list",
":",
"if",
"m",
"is",
"None",
"or",
"m",
".",
"judge",
"(",
"event",
")",
":",
"return",
"o"
] | Return first match for this event
:param event: an input event | [
"Return",
"first",
"match",
"for",
"this",
"event",
":",
"param",
"event",
":",
"an",
"input",
"event"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L166-L192 |
hubo1016/vlcp | vlcp/event/matchtree.py | EventTree.subtree | def subtree(self, event, create = False):
'''
Find a subtree from an event
'''
current = self
for i in range(self.depth, len(event.indices)):
if not hasattr(current, 'index'):
return current
ind = event.indices[i]
if create:
current = current.index.setdefault(ind, EventTree(current, self.branch))
current.parentIndex = ind
else:
current = current.index.get(ind)
if current is None:
return None
return current | python | def subtree(self, event, create = False):
'''
Find a subtree from an event
'''
current = self
for i in range(self.depth, len(event.indices)):
if not hasattr(current, 'index'):
return current
ind = event.indices[i]
if create:
current = current.index.setdefault(ind, EventTree(current, self.branch))
current.parentIndex = ind
else:
current = current.index.get(ind)
if current is None:
return None
return current | [
"def",
"subtree",
"(",
"self",
",",
"event",
",",
"create",
"=",
"False",
")",
":",
"current",
"=",
"self",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"depth",
",",
"len",
"(",
"event",
".",
"indices",
")",
")",
":",
"if",
"not",
"hasattr",
"(",
"current",
",",
"'index'",
")",
":",
"return",
"current",
"ind",
"=",
"event",
".",
"indices",
"[",
"i",
"]",
"if",
"create",
":",
"current",
"=",
"current",
".",
"index",
".",
"setdefault",
"(",
"ind",
",",
"EventTree",
"(",
"current",
",",
"self",
".",
"branch",
")",
")",
"current",
".",
"parentIndex",
"=",
"ind",
"else",
":",
"current",
"=",
"current",
".",
"index",
".",
"get",
"(",
"ind",
")",
"if",
"current",
"is",
"None",
":",
"return",
"None",
"return",
"current"
] | Find a subtree from an event | [
"Find",
"a",
"subtree",
"from",
"an",
"event"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/matchtree.py#L242-L258 |
hubo1016/vlcp | vlcp/utils/vxlandiscover.py | lognet_vxlan_walker | def lognet_vxlan_walker(prepush = True):
"""
Return a walker function to retrieve necessary information from ObjectDB
"""
def _walk_lognet(key, value, walk, save):
save(key)
if value is None:
return
try:
phynet = walk(value.physicalnetwork.getkey())
except KeyError:
pass
else:
if phynet is not None and getattr(phynet, 'type') == 'vxlan':
try:
vxlan_endpoint_key = VXLANEndpointSet.default_key(value.id)
walk(vxlan_endpoint_key)
except KeyError:
pass
else:
save(vxlan_endpoint_key)
if prepush:
# Acquire all logical ports
try:
netmap = walk(LogicalNetworkMap.default_key(value.id))
except KeyError:
pass
else:
save(netmap.getkey())
for logport in netmap.ports.dataset():
try:
_ = walk(logport.getkey())
except KeyError:
pass
else:
save(logport.getkey())
try:
_, (portid,) = LogicalPort._getIndices(logport.getkey())
portinfokey = LogicalPortVXLANInfo.default_key(portid)
_ = walk(portinfokey)
except KeyError:
pass
else:
save(portinfokey)
return _walk_lognet | python | def lognet_vxlan_walker(prepush = True):
"""
Return a walker function to retrieve necessary information from ObjectDB
"""
def _walk_lognet(key, value, walk, save):
save(key)
if value is None:
return
try:
phynet = walk(value.physicalnetwork.getkey())
except KeyError:
pass
else:
if phynet is not None and getattr(phynet, 'type') == 'vxlan':
try:
vxlan_endpoint_key = VXLANEndpointSet.default_key(value.id)
walk(vxlan_endpoint_key)
except KeyError:
pass
else:
save(vxlan_endpoint_key)
if prepush:
# Acquire all logical ports
try:
netmap = walk(LogicalNetworkMap.default_key(value.id))
except KeyError:
pass
else:
save(netmap.getkey())
for logport in netmap.ports.dataset():
try:
_ = walk(logport.getkey())
except KeyError:
pass
else:
save(logport.getkey())
try:
_, (portid,) = LogicalPort._getIndices(logport.getkey())
portinfokey = LogicalPortVXLANInfo.default_key(portid)
_ = walk(portinfokey)
except KeyError:
pass
else:
save(portinfokey)
return _walk_lognet | [
"def",
"lognet_vxlan_walker",
"(",
"prepush",
"=",
"True",
")",
":",
"def",
"_walk_lognet",
"(",
"key",
",",
"value",
",",
"walk",
",",
"save",
")",
":",
"save",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"phynet",
"=",
"walk",
"(",
"value",
".",
"physicalnetwork",
".",
"getkey",
"(",
")",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"phynet",
"is",
"not",
"None",
"and",
"getattr",
"(",
"phynet",
",",
"'type'",
")",
"==",
"'vxlan'",
":",
"try",
":",
"vxlan_endpoint_key",
"=",
"VXLANEndpointSet",
".",
"default_key",
"(",
"value",
".",
"id",
")",
"walk",
"(",
"vxlan_endpoint_key",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"save",
"(",
"vxlan_endpoint_key",
")",
"if",
"prepush",
":",
"# Acquire all logical ports",
"try",
":",
"netmap",
"=",
"walk",
"(",
"LogicalNetworkMap",
".",
"default_key",
"(",
"value",
".",
"id",
")",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"save",
"(",
"netmap",
".",
"getkey",
"(",
")",
")",
"for",
"logport",
"in",
"netmap",
".",
"ports",
".",
"dataset",
"(",
")",
":",
"try",
":",
"_",
"=",
"walk",
"(",
"logport",
".",
"getkey",
"(",
")",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"save",
"(",
"logport",
".",
"getkey",
"(",
")",
")",
"try",
":",
"_",
",",
"(",
"portid",
",",
")",
"=",
"LogicalPort",
".",
"_getIndices",
"(",
"logport",
".",
"getkey",
"(",
")",
")",
"portinfokey",
"=",
"LogicalPortVXLANInfo",
".",
"default_key",
"(",
"portid",
")",
"_",
"=",
"walk",
"(",
"portinfokey",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"save",
"(",
"portinfokey",
")",
"return",
"_walk_lognet"
] | Return a walker function to retrieve necessary information from ObjectDB | [
"Return",
"a",
"walker",
"function",
"to",
"retrieve",
"necessary",
"information",
"from",
"ObjectDB"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/vxlandiscover.py#L15-L59 |
hubo1016/vlcp | vlcp/utils/vxlandiscover.py | update_vxlaninfo | async def update_vxlaninfo(container, network_ip_dict, created_ports, removed_ports,
ovsdb_vhost, system_id, bridge,
allowedmigrationtime, refreshinterval):
'''
Do an ObjectDB transact to update all VXLAN informations
:param container: Routine container
:param network_ip_dict: a {logicalnetwork_id: tunnel_ip} dictionary
:param created_ports: logical ports to be added, a {logicalport_id: tunnel_ip} dictionary
:param removed_ports: logical ports to be removed, a {logicalport_id: tunnel_ip} dictionary
:param ovsdb_vhost: identifier for the bridge, vhost name
:param system_id: identifier for the bridge, OVSDB systemid
:param bridge: identifier for the bridge, bridge name
:param allowedmigrationtime: time allowed for port migration, secondary endpoint info will be removed
after this time
:param refreshinterval: refreshinterval * 2 will be the timeout for network endpoint
'''
network_list = list(network_ip_dict.keys())
vxlanendpoint_list = [VXLANEndpointSet.default_key(n) for n in network_list]
all_tun_ports2 = list(set(created_ports.keys()).union(set(removed_ports.keys())))
def update_vxlanendpoints(keys, values, timestamp):
# values = List[VXLANEndpointSet]
# endpointlist is [src_ip, vhost, systemid, bridge, expire]
for v,n in zip(values[0:len(network_list)], network_list):
if v is not None:
v.endpointlist = [ep for ep in v.endpointlist
if (ep[1], ep[2], ep[3]) != (ovsdb_vhost, system_id, bridge)
and ep[4] >= timestamp]
ip_address = network_ip_dict[n]
if ip_address is not None:
v.endpointlist.append([ip_address,
ovsdb_vhost,
system_id,
bridge,
None if refreshinterval is None else
refreshinterval * 1000000 * 2 + timestamp
])
written_values = {}
if all_tun_ports2:
for k,v,vxkey,vxinfo in zip(keys[len(network_list):len(network_list) + len(all_tun_ports2)],
values[len(network_list):len(network_list) + len(all_tun_ports2)],
keys[len(network_list) + len(all_tun_ports2):len(network_list) + 2 * len(all_tun_ports2)],
values[len(network_list) + len(all_tun_ports2):len(network_list) + 2 * len(all_tun_ports2)]):
if v is None:
if vxinfo is not None:
# The port is deleted? Then we should also delete the vxinfo
written_values[vxkey] = None
else:
if v.id in created_ports:
if vxinfo is None:
vxinfo = LogicalPortVXLANInfo.create_from_key(vxkey)
# There maybe more than one endpoint at the same time (on migrating)
# so we keep all possible endpoints, but move our endpoint to the first place
myendpoint = {'vhost': ovsdb_vhost,
'systemid': system_id,
'bridge': bridge,
'tunnel_dst': created_ports[v.id],
'updated_time': timestamp}
vxinfo.endpoints = [ep for ep in vxinfo.endpoints
if ep['updated_time'] + allowedmigrationtime * 1000000 >= timestamp
and (ep['vhost'], ep['systemid'], ep['bridge']) != (ovsdb_vhost, system_id, bridge)]
vxinfo.endpoints = [myendpoint] + vxinfo.endpoints
written_values[vxkey] = vxinfo
elif v.id in removed_ports:
if vxinfo is not None:
# Remove endpoint
vxinfo.endpoints = [ep for ep in vxinfo.endpoints
if (ep['vhost'], ep['systemid'], ep['bridge']) != (ovsdb_vhost, system_id, bridge)]
if not vxinfo.endpoints:
written_values[vxkey] = None
else:
written_values[vxkey] = vxinfo
written_values_list = tuple(written_values.items())
return (tuple(itertools.chain(keys[:len(network_list)], (k for k,_ in written_values_list))),
tuple(itertools.chain(values[:len(network_list)], (v for _,v in written_values_list))))
return await call_api(container, 'objectdb', 'transact', {'keys': tuple(vxlanendpoint_list + [LogicalPort.default_key(p) for p in all_tun_ports2] +
[LogicalPortVXLANInfo.default_key(p) for p in all_tun_ports2]),
'updater': update_vxlanendpoints,
'withtime': True
}) | python | async def update_vxlaninfo(container, network_ip_dict, created_ports, removed_ports,
ovsdb_vhost, system_id, bridge,
allowedmigrationtime, refreshinterval):
'''
Do an ObjectDB transact to update all VXLAN informations
:param container: Routine container
:param network_ip_dict: a {logicalnetwork_id: tunnel_ip} dictionary
:param created_ports: logical ports to be added, a {logicalport_id: tunnel_ip} dictionary
:param removed_ports: logical ports to be removed, a {logicalport_id: tunnel_ip} dictionary
:param ovsdb_vhost: identifier for the bridge, vhost name
:param system_id: identifier for the bridge, OVSDB systemid
:param bridge: identifier for the bridge, bridge name
:param allowedmigrationtime: time allowed for port migration, secondary endpoint info will be removed
after this time
:param refreshinterval: refreshinterval * 2 will be the timeout for network endpoint
'''
network_list = list(network_ip_dict.keys())
vxlanendpoint_list = [VXLANEndpointSet.default_key(n) for n in network_list]
all_tun_ports2 = list(set(created_ports.keys()).union(set(removed_ports.keys())))
def update_vxlanendpoints(keys, values, timestamp):
# values = List[VXLANEndpointSet]
# endpointlist is [src_ip, vhost, systemid, bridge, expire]
for v,n in zip(values[0:len(network_list)], network_list):
if v is not None:
v.endpointlist = [ep for ep in v.endpointlist
if (ep[1], ep[2], ep[3]) != (ovsdb_vhost, system_id, bridge)
and ep[4] >= timestamp]
ip_address = network_ip_dict[n]
if ip_address is not None:
v.endpointlist.append([ip_address,
ovsdb_vhost,
system_id,
bridge,
None if refreshinterval is None else
refreshinterval * 1000000 * 2 + timestamp
])
written_values = {}
if all_tun_ports2:
for k,v,vxkey,vxinfo in zip(keys[len(network_list):len(network_list) + len(all_tun_ports2)],
values[len(network_list):len(network_list) + len(all_tun_ports2)],
keys[len(network_list) + len(all_tun_ports2):len(network_list) + 2 * len(all_tun_ports2)],
values[len(network_list) + len(all_tun_ports2):len(network_list) + 2 * len(all_tun_ports2)]):
if v is None:
if vxinfo is not None:
# The port is deleted? Then we should also delete the vxinfo
written_values[vxkey] = None
else:
if v.id in created_ports:
if vxinfo is None:
vxinfo = LogicalPortVXLANInfo.create_from_key(vxkey)
# There maybe more than one endpoint at the same time (on migrating)
# so we keep all possible endpoints, but move our endpoint to the first place
myendpoint = {'vhost': ovsdb_vhost,
'systemid': system_id,
'bridge': bridge,
'tunnel_dst': created_ports[v.id],
'updated_time': timestamp}
vxinfo.endpoints = [ep for ep in vxinfo.endpoints
if ep['updated_time'] + allowedmigrationtime * 1000000 >= timestamp
and (ep['vhost'], ep['systemid'], ep['bridge']) != (ovsdb_vhost, system_id, bridge)]
vxinfo.endpoints = [myendpoint] + vxinfo.endpoints
written_values[vxkey] = vxinfo
elif v.id in removed_ports:
if vxinfo is not None:
# Remove endpoint
vxinfo.endpoints = [ep for ep in vxinfo.endpoints
if (ep['vhost'], ep['systemid'], ep['bridge']) != (ovsdb_vhost, system_id, bridge)]
if not vxinfo.endpoints:
written_values[vxkey] = None
else:
written_values[vxkey] = vxinfo
written_values_list = tuple(written_values.items())
return (tuple(itertools.chain(keys[:len(network_list)], (k for k,_ in written_values_list))),
tuple(itertools.chain(values[:len(network_list)], (v for _,v in written_values_list))))
return await call_api(container, 'objectdb', 'transact', {'keys': tuple(vxlanendpoint_list + [LogicalPort.default_key(p) for p in all_tun_ports2] +
[LogicalPortVXLANInfo.default_key(p) for p in all_tun_ports2]),
'updater': update_vxlanendpoints,
'withtime': True
}) | [
"async",
"def",
"update_vxlaninfo",
"(",
"container",
",",
"network_ip_dict",
",",
"created_ports",
",",
"removed_ports",
",",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
",",
"allowedmigrationtime",
",",
"refreshinterval",
")",
":",
"network_list",
"=",
"list",
"(",
"network_ip_dict",
".",
"keys",
"(",
")",
")",
"vxlanendpoint_list",
"=",
"[",
"VXLANEndpointSet",
".",
"default_key",
"(",
"n",
")",
"for",
"n",
"in",
"network_list",
"]",
"all_tun_ports2",
"=",
"list",
"(",
"set",
"(",
"created_ports",
".",
"keys",
"(",
")",
")",
".",
"union",
"(",
"set",
"(",
"removed_ports",
".",
"keys",
"(",
")",
")",
")",
")",
"def",
"update_vxlanendpoints",
"(",
"keys",
",",
"values",
",",
"timestamp",
")",
":",
"# values = List[VXLANEndpointSet]",
"# endpointlist is [src_ip, vhost, systemid, bridge, expire]",
"for",
"v",
",",
"n",
"in",
"zip",
"(",
"values",
"[",
"0",
":",
"len",
"(",
"network_list",
")",
"]",
",",
"network_list",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"v",
".",
"endpointlist",
"=",
"[",
"ep",
"for",
"ep",
"in",
"v",
".",
"endpointlist",
"if",
"(",
"ep",
"[",
"1",
"]",
",",
"ep",
"[",
"2",
"]",
",",
"ep",
"[",
"3",
"]",
")",
"!=",
"(",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
")",
"and",
"ep",
"[",
"4",
"]",
">=",
"timestamp",
"]",
"ip_address",
"=",
"network_ip_dict",
"[",
"n",
"]",
"if",
"ip_address",
"is",
"not",
"None",
":",
"v",
".",
"endpointlist",
".",
"append",
"(",
"[",
"ip_address",
",",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
",",
"None",
"if",
"refreshinterval",
"is",
"None",
"else",
"refreshinterval",
"*",
"1000000",
"*",
"2",
"+",
"timestamp",
"]",
")",
"written_values",
"=",
"{",
"}",
"if",
"all_tun_ports2",
":",
"for",
"k",
",",
"v",
",",
"vxkey",
",",
"vxinfo",
"in",
"zip",
"(",
"keys",
"[",
"len",
"(",
"network_list",
")",
":",
"len",
"(",
"network_list",
")",
"+",
"len",
"(",
"all_tun_ports2",
")",
"]",
",",
"values",
"[",
"len",
"(",
"network_list",
")",
":",
"len",
"(",
"network_list",
")",
"+",
"len",
"(",
"all_tun_ports2",
")",
"]",
",",
"keys",
"[",
"len",
"(",
"network_list",
")",
"+",
"len",
"(",
"all_tun_ports2",
")",
":",
"len",
"(",
"network_list",
")",
"+",
"2",
"*",
"len",
"(",
"all_tun_ports2",
")",
"]",
",",
"values",
"[",
"len",
"(",
"network_list",
")",
"+",
"len",
"(",
"all_tun_ports2",
")",
":",
"len",
"(",
"network_list",
")",
"+",
"2",
"*",
"len",
"(",
"all_tun_ports2",
")",
"]",
")",
":",
"if",
"v",
"is",
"None",
":",
"if",
"vxinfo",
"is",
"not",
"None",
":",
"# The port is deleted? Then we should also delete the vxinfo",
"written_values",
"[",
"vxkey",
"]",
"=",
"None",
"else",
":",
"if",
"v",
".",
"id",
"in",
"created_ports",
":",
"if",
"vxinfo",
"is",
"None",
":",
"vxinfo",
"=",
"LogicalPortVXLANInfo",
".",
"create_from_key",
"(",
"vxkey",
")",
"# There maybe more than one endpoint at the same time (on migrating)",
"# so we keep all possible endpoints, but move our endpoint to the first place",
"myendpoint",
"=",
"{",
"'vhost'",
":",
"ovsdb_vhost",
",",
"'systemid'",
":",
"system_id",
",",
"'bridge'",
":",
"bridge",
",",
"'tunnel_dst'",
":",
"created_ports",
"[",
"v",
".",
"id",
"]",
",",
"'updated_time'",
":",
"timestamp",
"}",
"vxinfo",
".",
"endpoints",
"=",
"[",
"ep",
"for",
"ep",
"in",
"vxinfo",
".",
"endpoints",
"if",
"ep",
"[",
"'updated_time'",
"]",
"+",
"allowedmigrationtime",
"*",
"1000000",
">=",
"timestamp",
"and",
"(",
"ep",
"[",
"'vhost'",
"]",
",",
"ep",
"[",
"'systemid'",
"]",
",",
"ep",
"[",
"'bridge'",
"]",
")",
"!=",
"(",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
")",
"]",
"vxinfo",
".",
"endpoints",
"=",
"[",
"myendpoint",
"]",
"+",
"vxinfo",
".",
"endpoints",
"written_values",
"[",
"vxkey",
"]",
"=",
"vxinfo",
"elif",
"v",
".",
"id",
"in",
"removed_ports",
":",
"if",
"vxinfo",
"is",
"not",
"None",
":",
"# Remove endpoint",
"vxinfo",
".",
"endpoints",
"=",
"[",
"ep",
"for",
"ep",
"in",
"vxinfo",
".",
"endpoints",
"if",
"(",
"ep",
"[",
"'vhost'",
"]",
",",
"ep",
"[",
"'systemid'",
"]",
",",
"ep",
"[",
"'bridge'",
"]",
")",
"!=",
"(",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
")",
"]",
"if",
"not",
"vxinfo",
".",
"endpoints",
":",
"written_values",
"[",
"vxkey",
"]",
"=",
"None",
"else",
":",
"written_values",
"[",
"vxkey",
"]",
"=",
"vxinfo",
"written_values_list",
"=",
"tuple",
"(",
"written_values",
".",
"items",
"(",
")",
")",
"return",
"(",
"tuple",
"(",
"itertools",
".",
"chain",
"(",
"keys",
"[",
":",
"len",
"(",
"network_list",
")",
"]",
",",
"(",
"k",
"for",
"k",
",",
"_",
"in",
"written_values_list",
")",
")",
")",
",",
"tuple",
"(",
"itertools",
".",
"chain",
"(",
"values",
"[",
":",
"len",
"(",
"network_list",
")",
"]",
",",
"(",
"v",
"for",
"_",
",",
"v",
"in",
"written_values_list",
")",
")",
")",
")",
"return",
"await",
"call_api",
"(",
"container",
",",
"'objectdb'",
",",
"'transact'",
",",
"{",
"'keys'",
":",
"tuple",
"(",
"vxlanendpoint_list",
"+",
"[",
"LogicalPort",
".",
"default_key",
"(",
"p",
")",
"for",
"p",
"in",
"all_tun_ports2",
"]",
"+",
"[",
"LogicalPortVXLANInfo",
".",
"default_key",
"(",
"p",
")",
"for",
"p",
"in",
"all_tun_ports2",
"]",
")",
",",
"'updater'",
":",
"update_vxlanendpoints",
",",
"'withtime'",
":",
"True",
"}",
")"
] | Do an ObjectDB transact to update all VXLAN informations
:param container: Routine container
:param network_ip_dict: a {logicalnetwork_id: tunnel_ip} dictionary
:param created_ports: logical ports to be added, a {logicalport_id: tunnel_ip} dictionary
:param removed_ports: logical ports to be removed, a {logicalport_id: tunnel_ip} dictionary
:param ovsdb_vhost: identifier for the bridge, vhost name
:param system_id: identifier for the bridge, OVSDB systemid
:param bridge: identifier for the bridge, bridge name
:param allowedmigrationtime: time allowed for port migration, secondary endpoint info will be removed
after this time
:param refreshinterval: refreshinterval * 2 will be the timeout for network endpoint | [
"Do",
"an",
"ObjectDB",
"transact",
"to",
"update",
"all",
"VXLAN",
"informations",
":",
"param",
"container",
":",
"Routine",
"container",
":",
"param",
"network_ip_dict",
":",
"a",
"{",
"logicalnetwork_id",
":",
"tunnel_ip",
"}",
"dictionary",
":",
"param",
"created_ports",
":",
"logical",
"ports",
"to",
"be",
"added",
"a",
"{",
"logicalport_id",
":",
"tunnel_ip",
"}",
"dictionary",
":",
"param",
"removed_ports",
":",
"logical",
"ports",
"to",
"be",
"removed",
"a",
"{",
"logicalport_id",
":",
"tunnel_ip",
"}",
"dictionary",
":",
"param",
"ovsdb_vhost",
":",
"identifier",
"for",
"the",
"bridge",
"vhost",
"name",
":",
"param",
"system_id",
":",
"identifier",
"for",
"the",
"bridge",
"OVSDB",
"systemid",
":",
"param",
"bridge",
":",
"identifier",
"for",
"the",
"bridge",
"bridge",
"name",
":",
"param",
"allowedmigrationtime",
":",
"time",
"allowed",
"for",
"port",
"migration",
"secondary",
"endpoint",
"info",
"will",
"be",
"removed",
"after",
"this",
"time",
":",
"param",
"refreshinterval",
":",
"refreshinterval",
"*",
"2",
"will",
"be",
"the",
"timeout",
"for",
"network",
"endpoint"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/vxlandiscover.py#L61-L148 |
hubo1016/vlcp | vlcp/utils/vxlandiscover.py | get_broadcast_ips | def get_broadcast_ips(vxlan_endpointset, local_ip, ovsdb_vhost, system_id, bridge):
'''
Get all IP addresses that are not local
:param vxlan_endpointset: a VXLANEndpointSet object
:param local_ips: list of local IP address to exclude with
:param ovsdb_vhost: identifier, vhost
:param system_id: identifier, system-id
:param bridge: identifier, bridge name
:return: `[(ip, ipnum)]` list where IPs are the original string of the IP address, and ipnum
are 32-bit numeric IPv4 address.
'''
localip_addr = _get_ip(local_ip)
allips = [(ip, ipnum) for ip, ipnum in ((ep[0], _get_ip(ep[0])) for ep in vxlan_endpointset.endpointlist
if (ep[1], ep[2], ep[3]) != (ovsdb_vhost, system_id, bridge))
if ipnum is not None and ipnum != localip_addr]
return allips | python | def get_broadcast_ips(vxlan_endpointset, local_ip, ovsdb_vhost, system_id, bridge):
'''
Get all IP addresses that are not local
:param vxlan_endpointset: a VXLANEndpointSet object
:param local_ips: list of local IP address to exclude with
:param ovsdb_vhost: identifier, vhost
:param system_id: identifier, system-id
:param bridge: identifier, bridge name
:return: `[(ip, ipnum)]` list where IPs are the original string of the IP address, and ipnum
are 32-bit numeric IPv4 address.
'''
localip_addr = _get_ip(local_ip)
allips = [(ip, ipnum) for ip, ipnum in ((ep[0], _get_ip(ep[0])) for ep in vxlan_endpointset.endpointlist
if (ep[1], ep[2], ep[3]) != (ovsdb_vhost, system_id, bridge))
if ipnum is not None and ipnum != localip_addr]
return allips | [
"def",
"get_broadcast_ips",
"(",
"vxlan_endpointset",
",",
"local_ip",
",",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
")",
":",
"localip_addr",
"=",
"_get_ip",
"(",
"local_ip",
")",
"allips",
"=",
"[",
"(",
"ip",
",",
"ipnum",
")",
"for",
"ip",
",",
"ipnum",
"in",
"(",
"(",
"ep",
"[",
"0",
"]",
",",
"_get_ip",
"(",
"ep",
"[",
"0",
"]",
")",
")",
"for",
"ep",
"in",
"vxlan_endpointset",
".",
"endpointlist",
"if",
"(",
"ep",
"[",
"1",
"]",
",",
"ep",
"[",
"2",
"]",
",",
"ep",
"[",
"3",
"]",
")",
"!=",
"(",
"ovsdb_vhost",
",",
"system_id",
",",
"bridge",
")",
")",
"if",
"ipnum",
"is",
"not",
"None",
"and",
"ipnum",
"!=",
"localip_addr",
"]",
"return",
"allips"
] | Get all IP addresses that are not local
:param vxlan_endpointset: a VXLANEndpointSet object
:param local_ips: list of local IP address to exclude with
:param ovsdb_vhost: identifier, vhost
:param system_id: identifier, system-id
:param bridge: identifier, bridge name
:return: `[(ip, ipnum)]` list where IPs are the original string of the IP address, and ipnum
are 32-bit numeric IPv4 address. | [
"Get",
"all",
"IP",
"addresses",
"that",
"are",
"not",
"local",
":",
"param",
"vxlan_endpointset",
":",
"a",
"VXLANEndpointSet",
"object",
":",
"param",
"local_ips",
":",
"list",
"of",
"local",
"IP",
"address",
"to",
"exclude",
"with",
":",
"param",
"ovsdb_vhost",
":",
"identifier",
"vhost",
":",
"param",
"system_id",
":",
"identifier",
"system",
"-",
"id",
":",
"param",
"bridge",
":",
"identifier",
"bridge",
"name",
":",
"return",
":",
"[",
"(",
"ip",
"ipnum",
")",
"]",
"list",
"where",
"IPs",
"are",
"the",
"original",
"string",
"of",
"the",
"IP",
"address",
"and",
"ipnum",
"are",
"32",
"-",
"bit",
"numeric",
"IPv4",
"address",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/vxlandiscover.py#L157-L178 |
hubo1016/vlcp | vlcp/event/future.py | Future.result | def result(self):
'''
:return: None if the result is not ready, the result from set_result, or raise the exception
from set_exception. If the result can be None, it is not possible to tell if the result is
available; use done() to determine that.
'''
try:
r = getattr(self, '_result')
except AttributeError:
return None
else:
if hasattr(self, '_exception'):
raise self._exception
else:
return r | python | def result(self):
'''
:return: None if the result is not ready, the result from set_result, or raise the exception
from set_exception. If the result can be None, it is not possible to tell if the result is
available; use done() to determine that.
'''
try:
r = getattr(self, '_result')
except AttributeError:
return None
else:
if hasattr(self, '_exception'):
raise self._exception
else:
return r | [
"def",
"result",
"(",
"self",
")",
":",
"try",
":",
"r",
"=",
"getattr",
"(",
"self",
",",
"'_result'",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_exception'",
")",
":",
"raise",
"self",
".",
"_exception",
"else",
":",
"return",
"r"
] | :return: None if the result is not ready, the result from set_result, or raise the exception
from set_exception. If the result can be None, it is not possible to tell if the result is
available; use done() to determine that. | [
":",
"return",
":",
"None",
"if",
"the",
"result",
"is",
"not",
"ready",
"the",
"result",
"from",
"set_result",
"or",
"raise",
"the",
"exception",
"from",
"set_exception",
".",
"If",
"the",
"result",
"can",
"be",
"None",
"it",
"is",
"not",
"possible",
"to",
"tell",
"if",
"the",
"result",
"is",
"available",
";",
"use",
"done",
"()",
"to",
"determine",
"that",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/future.py#L57-L71 |
hubo1016/vlcp | vlcp/event/future.py | Future.wait | async def wait(self, container = None):
'''
:param container: DEPRECATED container of current routine
:return: The result, or raise the exception from set_exception.
'''
if hasattr(self, '_result'):
if hasattr(self, '_exception'):
raise self._exception
else:
return self._result
else:
ev = await FutureEvent.createMatcher(self)
if hasattr(ev, 'exception'):
raise ev.exception
else:
return ev.result | python | async def wait(self, container = None):
'''
:param container: DEPRECATED container of current routine
:return: The result, or raise the exception from set_exception.
'''
if hasattr(self, '_result'):
if hasattr(self, '_exception'):
raise self._exception
else:
return self._result
else:
ev = await FutureEvent.createMatcher(self)
if hasattr(ev, 'exception'):
raise ev.exception
else:
return ev.result | [
"async",
"def",
"wait",
"(",
"self",
",",
"container",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_result'",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_exception'",
")",
":",
"raise",
"self",
".",
"_exception",
"else",
":",
"return",
"self",
".",
"_result",
"else",
":",
"ev",
"=",
"await",
"FutureEvent",
".",
"createMatcher",
"(",
"self",
")",
"if",
"hasattr",
"(",
"ev",
",",
"'exception'",
")",
":",
"raise",
"ev",
".",
"exception",
"else",
":",
"return",
"ev",
".",
"result"
] | :param container: DEPRECATED container of current routine
:return: The result, or raise the exception from set_exception. | [
":",
"param",
"container",
":",
"DEPRECATED",
"container",
"of",
"current",
"routine",
":",
"return",
":",
"The",
"result",
"or",
"raise",
"the",
"exception",
"from",
"set_exception",
"."
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/future.py#L72-L88 |
hubo1016/vlcp | vlcp/event/future.py | Future.set_result | def set_result(self, result):
'''
Set the result to Future object, wake up all the waiters
:param result: result to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = result
self._scheduler.emergesend(FutureEvent(self, result = result)) | python | def set_result(self, result):
'''
Set the result to Future object, wake up all the waiters
:param result: result to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = result
self._scheduler.emergesend(FutureEvent(self, result = result)) | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_result'",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot set the result twice'",
")",
"self",
".",
"_result",
"=",
"result",
"self",
".",
"_scheduler",
".",
"emergesend",
"(",
"FutureEvent",
"(",
"self",
",",
"result",
"=",
"result",
")",
")"
] | Set the result to Future object, wake up all the waiters
:param result: result to set | [
"Set",
"the",
"result",
"to",
"Future",
"object",
"wake",
"up",
"all",
"the",
"waiters",
":",
"param",
"result",
":",
"result",
"to",
"set"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/future.py#L89-L98 |
hubo1016/vlcp | vlcp/event/future.py | Future.set_exception | def set_exception(self, exception):
'''
Set an exception to Future object, wake up all the waiters
:param exception: exception to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = None
self._exception = exception
self._scheduler.emergesend(FutureEvent(self, exception = exception)) | python | def set_exception(self, exception):
'''
Set an exception to Future object, wake up all the waiters
:param exception: exception to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = None
self._exception = exception
self._scheduler.emergesend(FutureEvent(self, exception = exception)) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_result'",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot set the result twice'",
")",
"self",
".",
"_result",
"=",
"None",
"self",
".",
"_exception",
"=",
"exception",
"self",
".",
"_scheduler",
".",
"emergesend",
"(",
"FutureEvent",
"(",
"self",
",",
"exception",
"=",
"exception",
")",
")"
] | Set an exception to Future object, wake up all the waiters
:param exception: exception to set | [
"Set",
"an",
"exception",
"to",
"Future",
"object",
"wake",
"up",
"all",
"the",
"waiters",
":",
"param",
"exception",
":",
"exception",
"to",
"set"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/future.py#L99-L109 |
hubo1016/vlcp | vlcp/event/future.py | Future.ensure_result | def ensure_result(self, supress_exception = False, defaultresult = None):
'''
Context manager to ensure returning the result
'''
try:
yield self
except Exception as exc:
if not self.done():
self.set_exception(exc)
if not supress_exception:
raise
except:
if not self.done():
self.set_exception(FutureCancelledException('cancelled'))
raise
else:
if not self.done():
self.set_result(defaultresult) | python | def ensure_result(self, supress_exception = False, defaultresult = None):
'''
Context manager to ensure returning the result
'''
try:
yield self
except Exception as exc:
if not self.done():
self.set_exception(exc)
if not supress_exception:
raise
except:
if not self.done():
self.set_exception(FutureCancelledException('cancelled'))
raise
else:
if not self.done():
self.set_result(defaultresult) | [
"def",
"ensure_result",
"(",
"self",
",",
"supress_exception",
"=",
"False",
",",
"defaultresult",
"=",
"None",
")",
":",
"try",
":",
"yield",
"self",
"except",
"Exception",
"as",
"exc",
":",
"if",
"not",
"self",
".",
"done",
"(",
")",
":",
"self",
".",
"set_exception",
"(",
"exc",
")",
"if",
"not",
"supress_exception",
":",
"raise",
"except",
":",
"if",
"not",
"self",
".",
"done",
"(",
")",
":",
"self",
".",
"set_exception",
"(",
"FutureCancelledException",
"(",
"'cancelled'",
")",
")",
"raise",
"else",
":",
"if",
"not",
"self",
".",
"done",
"(",
")",
":",
"self",
".",
"set_result",
"(",
"defaultresult",
")"
] | Context manager to ensure returning the result | [
"Context",
"manager",
"to",
"ensure",
"returning",
"the",
"result"
] | train | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/future.py#L111-L128 |
pudo/datafreeze | datafreeze/app.py | freeze | def freeze(result, format='csv', filename='freeze.csv', fileobj=None,
prefix='.', mode='list', **kw):
"""
Perform a data export of a given result set. This is a very
flexible exporter, allowing for various output formats, metadata
assignment, and file name templating to dump each record (or a set
of records) into individual files.
::
result = db['person'].all()
dataset.freeze(result, format='json', filename='all-persons.json')
Instead of passing in the file name, you can also pass a file object::
result = db['person'].all()
fh = open('/dev/null', 'wb')
dataset.freeze(result, format='json', fileobj=fh)
Be aware that this will disable file name templating and store all
results to the same file.
If ``result`` is a table (rather than a result set), all records in
the table are exported (as if ``result.all()`` had been called).
freeze supports two values for ``mode``:
*list* (default)
The entire result set is dumped into a single file.
*item*
One file is created for each row in the result set.
You should set a ``filename`` for the exported file(s). If ``mode``
is set to *item* the function would generate one file per row. In
that case you can use values as placeholders in filenames::
dataset.freeze(res, mode='item', format='json',
filename='item-{{id}}.json')
The following output ``format`` s are supported:
*csv*
Comma-separated values, first line contains column names.
*json*
A JSON file containing a list of dictionaries for each row
in the table. If a ``callback`` is given, JSON with padding
(JSONP) will be generated.
*tabson*
Tabson is a smart combination of the space-efficiency of the
CSV and the parsability and structure of JSON.
You can pass additional named parameters specific to the used format.
As an example, you can freeze to minified JSON with the following:
dataset.freeze(res, format='json', indent=4, wrap=False,
filename='output.json')
*json* and *tabson*
*callback*:
if provided, generate a JSONP string using the given callback
function, i.e. something like `callback && callback({...})`
*indent*:
if *indent* is a non-negative integer (it is ``2`` by default
when you call `dataset.freeze`, and ``None`` via the
``datafreeze`` command), then JSON array elements and object
members will be pretty-printed with that indent level.
An indent level of 0 will only insert newlines.
``None`` is the most compact representation.
*meta*:
if *meta* is not ``None`` (default: ``{}``), it will be included
in the JSON output (for *json*, only if *wrap* is ``True``).
*wrap* (only for *json*):
if *wrap* is ``True`` (default), the JSON output is an object
of the form ``{"count": 2, "results": [...]}``.
if ``meta`` is not ``None``, a third property ``meta`` is added
to the wrapping object, with this value.
"""
kw.update({
'format': format,
'filename': filename,
'fileobj': fileobj,
'prefix': prefix,
'mode': mode
})
# Special cases when freezing comes from dataset.freeze
if format in ['json', 'tabson'] and 'indent' not in kw:
kw['indent'] = 2
records = result.all() if isinstance(result, dataset.Table) else result
return freeze_export(Export({}, kw), result=records) | python | def freeze(result, format='csv', filename='freeze.csv', fileobj=None,
prefix='.', mode='list', **kw):
"""
Perform a data export of a given result set. This is a very
flexible exporter, allowing for various output formats, metadata
assignment, and file name templating to dump each record (or a set
of records) into individual files.
::
result = db['person'].all()
dataset.freeze(result, format='json', filename='all-persons.json')
Instead of passing in the file name, you can also pass a file object::
result = db['person'].all()
fh = open('/dev/null', 'wb')
dataset.freeze(result, format='json', fileobj=fh)
Be aware that this will disable file name templating and store all
results to the same file.
If ``result`` is a table (rather than a result set), all records in
the table are exported (as if ``result.all()`` had been called).
freeze supports two values for ``mode``:
*list* (default)
The entire result set is dumped into a single file.
*item*
One file is created for each row in the result set.
You should set a ``filename`` for the exported file(s). If ``mode``
is set to *item* the function would generate one file per row. In
that case you can use values as placeholders in filenames::
dataset.freeze(res, mode='item', format='json',
filename='item-{{id}}.json')
The following output ``format`` s are supported:
*csv*
Comma-separated values, first line contains column names.
*json*
A JSON file containing a list of dictionaries for each row
in the table. If a ``callback`` is given, JSON with padding
(JSONP) will be generated.
*tabson*
Tabson is a smart combination of the space-efficiency of the
CSV and the parsability and structure of JSON.
You can pass additional named parameters specific to the used format.
As an example, you can freeze to minified JSON with the following:
dataset.freeze(res, format='json', indent=4, wrap=False,
filename='output.json')
*json* and *tabson*
*callback*:
if provided, generate a JSONP string using the given callback
function, i.e. something like `callback && callback({...})`
*indent*:
if *indent* is a non-negative integer (it is ``2`` by default
when you call `dataset.freeze`, and ``None`` via the
``datafreeze`` command), then JSON array elements and object
members will be pretty-printed with that indent level.
An indent level of 0 will only insert newlines.
``None`` is the most compact representation.
*meta*:
if *meta* is not ``None`` (default: ``{}``), it will be included
in the JSON output (for *json*, only if *wrap* is ``True``).
*wrap* (only for *json*):
if *wrap* is ``True`` (default), the JSON output is an object
of the form ``{"count": 2, "results": [...]}``.
if ``meta`` is not ``None``, a third property ``meta`` is added
to the wrapping object, with this value.
"""
kw.update({
'format': format,
'filename': filename,
'fileobj': fileobj,
'prefix': prefix,
'mode': mode
})
# Special cases when freezing comes from dataset.freeze
if format in ['json', 'tabson'] and 'indent' not in kw:
kw['indent'] = 2
records = result.all() if isinstance(result, dataset.Table) else result
return freeze_export(Export({}, kw), result=records) | [
"def",
"freeze",
"(",
"result",
",",
"format",
"=",
"'csv'",
",",
"filename",
"=",
"'freeze.csv'",
",",
"fileobj",
"=",
"None",
",",
"prefix",
"=",
"'.'",
",",
"mode",
"=",
"'list'",
",",
"*",
"*",
"kw",
")",
":",
"kw",
".",
"update",
"(",
"{",
"'format'",
":",
"format",
",",
"'filename'",
":",
"filename",
",",
"'fileobj'",
":",
"fileobj",
",",
"'prefix'",
":",
"prefix",
",",
"'mode'",
":",
"mode",
"}",
")",
"# Special cases when freezing comes from dataset.freeze",
"if",
"format",
"in",
"[",
"'json'",
",",
"'tabson'",
"]",
"and",
"'indent'",
"not",
"in",
"kw",
":",
"kw",
"[",
"'indent'",
"]",
"=",
"2",
"records",
"=",
"result",
".",
"all",
"(",
")",
"if",
"isinstance",
"(",
"result",
",",
"dataset",
".",
"Table",
")",
"else",
"result",
"return",
"freeze_export",
"(",
"Export",
"(",
"{",
"}",
",",
"kw",
")",
",",
"result",
"=",
"records",
")"
] | Perform a data export of a given result set. This is a very
flexible exporter, allowing for various output formats, metadata
assignment, and file name templating to dump each record (or a set
of records) into individual files.
::
result = db['person'].all()
dataset.freeze(result, format='json', filename='all-persons.json')
Instead of passing in the file name, you can also pass a file object::
result = db['person'].all()
fh = open('/dev/null', 'wb')
dataset.freeze(result, format='json', fileobj=fh)
Be aware that this will disable file name templating and store all
results to the same file.
If ``result`` is a table (rather than a result set), all records in
the table are exported (as if ``result.all()`` had been called).
freeze supports two values for ``mode``:
*list* (default)
The entire result set is dumped into a single file.
*item*
One file is created for each row in the result set.
You should set a ``filename`` for the exported file(s). If ``mode``
is set to *item* the function would generate one file per row. In
that case you can use values as placeholders in filenames::
dataset.freeze(res, mode='item', format='json',
filename='item-{{id}}.json')
The following output ``format`` s are supported:
*csv*
Comma-separated values, first line contains column names.
*json*
A JSON file containing a list of dictionaries for each row
in the table. If a ``callback`` is given, JSON with padding
(JSONP) will be generated.
*tabson*
Tabson is a smart combination of the space-efficiency of the
CSV and the parsability and structure of JSON.
You can pass additional named parameters specific to the used format.
As an example, you can freeze to minified JSON with the following:
dataset.freeze(res, format='json', indent=4, wrap=False,
filename='output.json')
*json* and *tabson*
*callback*:
if provided, generate a JSONP string using the given callback
function, i.e. something like `callback && callback({...})`
*indent*:
if *indent* is a non-negative integer (it is ``2`` by default
when you call `dataset.freeze`, and ``None`` via the
``datafreeze`` command), then JSON array elements and object
members will be pretty-printed with that indent level.
An indent level of 0 will only insert newlines.
``None`` is the most compact representation.
*meta*:
if *meta* is not ``None`` (default: ``{}``), it will be included
in the JSON output (for *json*, only if *wrap* is ``True``).
*wrap* (only for *json*):
if *wrap* is ``True`` (default), the JSON output is an object
of the form ``{"count": 2, "results": [...]}``.
if ``meta`` is not ``None``, a third property ``meta`` is added
to the wrapping object, with this value. | [
"Perform",
"a",
"data",
"export",
"of",
"a",
"given",
"result",
"set",
".",
"This",
"is",
"a",
"very",
"flexible",
"exporter",
"allowing",
"for",
"various",
"output",
"formats",
"metadata",
"assignment",
"and",
"file",
"name",
"templating",
"to",
"dump",
"each",
"record",
"(",
"or",
"a",
"set",
"of",
"records",
")",
"into",
"individual",
"files",
"."
] | train | https://github.com/pudo/datafreeze/blob/adbb19ad71a9a6cec1fbec650ee1e784c33eae8e/datafreeze/app.py#L26-L124 |
rbit/pydtls | dtls/x509.py | decode_cert | def decode_cert(cert):
"""Convert an X509 certificate into a Python dictionary
This function converts the given X509 certificate into a Python dictionary
in the manner established by the Python standard library's ssl module.
"""
ret_dict = {}
subject_xname = X509_get_subject_name(cert.value)
ret_dict["subject"] = _create_tuple_for_X509_NAME(subject_xname)
notAfter = X509_get_notAfter(cert.value)
ret_dict["notAfter"] = ASN1_TIME_print(notAfter)
peer_alt_names = _get_peer_alt_names(cert)
if peer_alt_names is not None:
ret_dict["subjectAltName"] = peer_alt_names
return ret_dict | python | def decode_cert(cert):
"""Convert an X509 certificate into a Python dictionary
This function converts the given X509 certificate into a Python dictionary
in the manner established by the Python standard library's ssl module.
"""
ret_dict = {}
subject_xname = X509_get_subject_name(cert.value)
ret_dict["subject"] = _create_tuple_for_X509_NAME(subject_xname)
notAfter = X509_get_notAfter(cert.value)
ret_dict["notAfter"] = ASN1_TIME_print(notAfter)
peer_alt_names = _get_peer_alt_names(cert)
if peer_alt_names is not None:
ret_dict["subjectAltName"] = peer_alt_names
return ret_dict | [
"def",
"decode_cert",
"(",
"cert",
")",
":",
"ret_dict",
"=",
"{",
"}",
"subject_xname",
"=",
"X509_get_subject_name",
"(",
"cert",
".",
"value",
")",
"ret_dict",
"[",
"\"subject\"",
"]",
"=",
"_create_tuple_for_X509_NAME",
"(",
"subject_xname",
")",
"notAfter",
"=",
"X509_get_notAfter",
"(",
"cert",
".",
"value",
")",
"ret_dict",
"[",
"\"notAfter\"",
"]",
"=",
"ASN1_TIME_print",
"(",
"notAfter",
")",
"peer_alt_names",
"=",
"_get_peer_alt_names",
"(",
"cert",
")",
"if",
"peer_alt_names",
"is",
"not",
"None",
":",
"ret_dict",
"[",
"\"subjectAltName\"",
"]",
"=",
"peer_alt_names",
"return",
"ret_dict"
] | Convert an X509 certificate into a Python dictionary
This function converts the given X509 certificate into a Python dictionary
in the manner established by the Python standard library's ssl module. | [
"Convert",
"an",
"X509",
"certificate",
"into",
"a",
"Python",
"dictionary"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/x509.py#L61-L79 |
rbit/pydtls | dtls/patch.py | _get_server_certificate | def _get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
"""Retrieve a server certificate
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt.
"""
if ssl_version not in (PROTOCOL_DTLS, PROTOCOL_DTLSv1, PROTOCOL_DTLSv1_2):
return _orig_get_server_certificate(addr, ssl_version, ca_certs)
if ca_certs is not None:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
af = getaddrinfo(addr[0], addr[1])[0][0]
s = ssl.wrap_socket(socket(af, SOCK_DGRAM),
ssl_version=ssl_version,
cert_reqs=cert_reqs, ca_certs=ca_certs)
s.connect(addr)
dercert = s.getpeercert(True)
s.close()
return ssl.DER_cert_to_PEM_cert(dercert) | python | def _get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
"""Retrieve a server certificate
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt.
"""
if ssl_version not in (PROTOCOL_DTLS, PROTOCOL_DTLSv1, PROTOCOL_DTLSv1_2):
return _orig_get_server_certificate(addr, ssl_version, ca_certs)
if ca_certs is not None:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
af = getaddrinfo(addr[0], addr[1])[0][0]
s = ssl.wrap_socket(socket(af, SOCK_DGRAM),
ssl_version=ssl_version,
cert_reqs=cert_reqs, ca_certs=ca_certs)
s.connect(addr)
dercert = s.getpeercert(True)
s.close()
return ssl.DER_cert_to_PEM_cert(dercert) | [
"def",
"_get_server_certificate",
"(",
"addr",
",",
"ssl_version",
"=",
"PROTOCOL_SSLv23",
",",
"ca_certs",
"=",
"None",
")",
":",
"if",
"ssl_version",
"not",
"in",
"(",
"PROTOCOL_DTLS",
",",
"PROTOCOL_DTLSv1",
",",
"PROTOCOL_DTLSv1_2",
")",
":",
"return",
"_orig_get_server_certificate",
"(",
"addr",
",",
"ssl_version",
",",
"ca_certs",
")",
"if",
"ca_certs",
"is",
"not",
"None",
":",
"cert_reqs",
"=",
"ssl",
".",
"CERT_REQUIRED",
"else",
":",
"cert_reqs",
"=",
"ssl",
".",
"CERT_NONE",
"af",
"=",
"getaddrinfo",
"(",
"addr",
"[",
"0",
"]",
",",
"addr",
"[",
"1",
"]",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"s",
"=",
"ssl",
".",
"wrap_socket",
"(",
"socket",
"(",
"af",
",",
"SOCK_DGRAM",
")",
",",
"ssl_version",
"=",
"ssl_version",
",",
"cert_reqs",
"=",
"cert_reqs",
",",
"ca_certs",
"=",
"ca_certs",
")",
"s",
".",
"connect",
"(",
"addr",
")",
"dercert",
"=",
"s",
".",
"getpeercert",
"(",
"True",
")",
"s",
".",
"close",
"(",
")",
"return",
"ssl",
".",
"DER_cert_to_PEM_cert",
"(",
"dercert",
")"
] | Retrieve a server certificate
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt. | [
"Retrieve",
"a",
"server",
"certificate"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/patch.py#L100-L123 |
rbit/pydtls | dtls/sslconnection.py | SSLContext.set_curves | def set_curves(self, curves):
u''' Set supported curves by name, nid or nist.
:param str | tuple(int) curves: Example "secp384r1:secp256k1", (715, 714), "P-384", "K-409:B-409:K-571", ...
:return: 1 for success and 0 for failure
'''
retVal = None
if isinstance(curves, str):
retVal = SSL_CTX_set1_curves_list(self._ctx, curves)
elif isinstance(curves, tuple):
retVal = SSL_CTX_set1_curves(self._ctx, curves, len(curves))
return retVal | python | def set_curves(self, curves):
u''' Set supported curves by name, nid or nist.
:param str | tuple(int) curves: Example "secp384r1:secp256k1", (715, 714), "P-384", "K-409:B-409:K-571", ...
:return: 1 for success and 0 for failure
'''
retVal = None
if isinstance(curves, str):
retVal = SSL_CTX_set1_curves_list(self._ctx, curves)
elif isinstance(curves, tuple):
retVal = SSL_CTX_set1_curves(self._ctx, curves, len(curves))
return retVal | [
"def",
"set_curves",
"(",
"self",
",",
"curves",
")",
":",
"retVal",
"=",
"None",
"if",
"isinstance",
"(",
"curves",
",",
"str",
")",
":",
"retVal",
"=",
"SSL_CTX_set1_curves_list",
"(",
"self",
".",
"_ctx",
",",
"curves",
")",
"elif",
"isinstance",
"(",
"curves",
",",
"tuple",
")",
":",
"retVal",
"=",
"SSL_CTX_set1_curves",
"(",
"self",
".",
"_ctx",
",",
"curves",
",",
"len",
"(",
"curves",
")",
")",
"return",
"retVal"
] | u''' Set supported curves by name, nid or nist.
:param str | tuple(int) curves: Example "secp384r1:secp256k1", (715, 714), "P-384", "K-409:B-409:K-571", ...
:return: 1 for success and 0 for failure | [
"u",
"Set",
"supported",
"curves",
"by",
"name",
"nid",
"or",
"nist",
"."
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L206-L217 |
rbit/pydtls | dtls/sslconnection.py | SSLContext.set_ecdh_curve | def set_ecdh_curve(self, curve_name=None):
u''' Select a curve to use for ECDH(E) key exchange or set it to auto mode
Used for server only!
s.a. openssl.exe ecparam -list_curves
:param None | str curve_name: None = Auto-mode, "secp256k1", "secp384r1", ...
:return: 1 for success and 0 for failure
'''
if curve_name:
retVal = SSL_CTX_set_ecdh_auto(self._ctx, 0)
avail_curves = get_elliptic_curves()
key = [curve for curve in avail_curves if curve.name == curve_name][0].to_EC_KEY()
retVal &= SSL_CTX_set_tmp_ecdh(self._ctx, key)
else:
retVal = SSL_CTX_set_ecdh_auto(self._ctx, 1)
return retVal | python | def set_ecdh_curve(self, curve_name=None):
u''' Select a curve to use for ECDH(E) key exchange or set it to auto mode
Used for server only!
s.a. openssl.exe ecparam -list_curves
:param None | str curve_name: None = Auto-mode, "secp256k1", "secp384r1", ...
:return: 1 for success and 0 for failure
'''
if curve_name:
retVal = SSL_CTX_set_ecdh_auto(self._ctx, 0)
avail_curves = get_elliptic_curves()
key = [curve for curve in avail_curves if curve.name == curve_name][0].to_EC_KEY()
retVal &= SSL_CTX_set_tmp_ecdh(self._ctx, key)
else:
retVal = SSL_CTX_set_ecdh_auto(self._ctx, 1)
return retVal | [
"def",
"set_ecdh_curve",
"(",
"self",
",",
"curve_name",
"=",
"None",
")",
":",
"if",
"curve_name",
":",
"retVal",
"=",
"SSL_CTX_set_ecdh_auto",
"(",
"self",
".",
"_ctx",
",",
"0",
")",
"avail_curves",
"=",
"get_elliptic_curves",
"(",
")",
"key",
"=",
"[",
"curve",
"for",
"curve",
"in",
"avail_curves",
"if",
"curve",
".",
"name",
"==",
"curve_name",
"]",
"[",
"0",
"]",
".",
"to_EC_KEY",
"(",
")",
"retVal",
"&=",
"SSL_CTX_set_tmp_ecdh",
"(",
"self",
".",
"_ctx",
",",
"key",
")",
"else",
":",
"retVal",
"=",
"SSL_CTX_set_ecdh_auto",
"(",
"self",
".",
"_ctx",
",",
"1",
")",
"return",
"retVal"
] | u''' Select a curve to use for ECDH(E) key exchange or set it to auto mode
Used for server only!
s.a. openssl.exe ecparam -list_curves
:param None | str curve_name: None = Auto-mode, "secp256k1", "secp384r1", ...
:return: 1 for success and 0 for failure | [
"u",
"Select",
"a",
"curve",
"to",
"use",
"for",
"ECDH",
"(",
"E",
")",
"key",
"exchange",
"or",
"set",
"it",
"to",
"auto",
"mode"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L238-L255 |
rbit/pydtls | dtls/sslconnection.py | SSLContext.build_cert_chain | def build_cert_chain(self, flags=SSL_BUILD_CHAIN_FLAG_NONE):
u'''
Used for server side only!
:param flags:
:return: 1 for success and 0 for failure
'''
retVal = SSL_CTX_build_cert_chain(self._ctx, flags)
return retVal | python | def build_cert_chain(self, flags=SSL_BUILD_CHAIN_FLAG_NONE):
u'''
Used for server side only!
:param flags:
:return: 1 for success and 0 for failure
'''
retVal = SSL_CTX_build_cert_chain(self._ctx, flags)
return retVal | [
"def",
"build_cert_chain",
"(",
"self",
",",
"flags",
"=",
"SSL_BUILD_CHAIN_FLAG_NONE",
")",
":",
"retVal",
"=",
"SSL_CTX_build_cert_chain",
"(",
"self",
".",
"_ctx",
",",
"flags",
")",
"return",
"retVal"
] | u'''
Used for server side only!
:param flags:
:return: 1 for success and 0 for failure | [
"u",
"Used",
"for",
"server",
"side",
"only!"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L257-L265 |
rbit/pydtls | dtls/sslconnection.py | SSLContext.set_ssl_logging | def set_ssl_logging(self, enable=False, func=_ssl_logging_cb):
u''' Enable or disable SSL logging
:param True | False enable: Enable or disable SSL logging
:param func: Callback function for logging
'''
if enable:
SSL_CTX_set_info_callback(self._ctx, func)
else:
SSL_CTX_set_info_callback(self._ctx, 0) | python | def set_ssl_logging(self, enable=False, func=_ssl_logging_cb):
u''' Enable or disable SSL logging
:param True | False enable: Enable or disable SSL logging
:param func: Callback function for logging
'''
if enable:
SSL_CTX_set_info_callback(self._ctx, func)
else:
SSL_CTX_set_info_callback(self._ctx, 0) | [
"def",
"set_ssl_logging",
"(",
"self",
",",
"enable",
"=",
"False",
",",
"func",
"=",
"_ssl_logging_cb",
")",
":",
"if",
"enable",
":",
"SSL_CTX_set_info_callback",
"(",
"self",
".",
"_ctx",
",",
"func",
")",
"else",
":",
"SSL_CTX_set_info_callback",
"(",
"self",
".",
"_ctx",
",",
"0",
")"
] | u''' Enable or disable SSL logging
:param True | False enable: Enable or disable SSL logging
:param func: Callback function for logging | [
"u",
"Enable",
"or",
"disable",
"SSL",
"logging"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L267-L276 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.get_socket | def get_socket(self, inbound):
"""Retrieve a socket used by this connection
When inbound is True, then the socket from which this connection reads
data is retrieved. Otherwise the socket to which this connection writes
data is retrieved.
Read and write sockets differ depending on whether this is a server- or
a client-side connection, and on whether a routing demux is in use.
"""
if inbound and hasattr(self, "_rsock"):
return self._rsock
return self._sock | python | def get_socket(self, inbound):
"""Retrieve a socket used by this connection
When inbound is True, then the socket from which this connection reads
data is retrieved. Otherwise the socket to which this connection writes
data is retrieved.
Read and write sockets differ depending on whether this is a server- or
a client-side connection, and on whether a routing demux is in use.
"""
if inbound and hasattr(self, "_rsock"):
return self._rsock
return self._sock | [
"def",
"get_socket",
"(",
"self",
",",
"inbound",
")",
":",
"if",
"inbound",
"and",
"hasattr",
"(",
"self",
",",
"\"_rsock\"",
")",
":",
"return",
"self",
".",
"_rsock",
"return",
"self",
".",
"_sock"
] | Retrieve a socket used by this connection
When inbound is True, then the socket from which this connection reads
data is retrieved. Otherwise the socket to which this connection writes
data is retrieved.
Read and write sockets differ depending on whether this is a server- or
a client-side connection, and on whether a routing demux is in use. | [
"Retrieve",
"a",
"socket",
"used",
"by",
"this",
"connection"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L575-L588 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.listen | def listen(self):
"""Server-side cookie exchange
This method reads datagrams from the socket and initiates cookie
exchange, upon whose successful conclusion one can then proceed to
the accept method. Alternatively, accept can be called directly, in
which case it will call this method. In order to prevent denial-of-
service attacks, only a small, constant set of computing resources
are used during the listen phase.
On some platforms, listen must be called so that packets will be
forwarded to accepted connections. Doing so is therefore recommened
in all cases for portable code.
Return value: a peer address if a datagram from a new peer was
encountered, None if a datagram for a known peer was forwarded
"""
if not hasattr(self, "_listening"):
raise InvalidSocketError("listen called on non-listening socket")
self._pending_peer_address = None
try:
peer_address = self._udp_demux.service()
except socket.timeout:
peer_address = None
except socket.error as sock_err:
if sock_err.errno != errno.EWOULDBLOCK:
_logger.exception("Unexpected socket error in listen")
raise
peer_address = None
if not peer_address:
_logger.debug("Listen returning without peer")
return
# The demux advises that a datagram from a new peer may have arrived
if type(peer_address) is tuple:
# For this type of demux, the write BIO must be pointed at the peer
BIO_dgram_set_peer(self._wbio.value, peer_address)
self._udp_demux.forward()
self._listening_peer_address = peer_address
self._check_nbio()
self._listening = True
try:
_logger.debug("Invoking DTLSv1_listen for ssl: %d",
self._ssl.raw)
dtls_peer_address = DTLSv1_listen(self._ssl.value)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_WANT_READ:
# This method must be called again to forward the next datagram
_logger.debug("DTLSv1_listen must be resumed")
return
elif err.errqueue and err.errqueue[0][0] == ERR_WRONG_VERSION_NUMBER:
_logger.debug("Wrong version number; aborting handshake")
raise
elif err.errqueue and err.errqueue[0][0] == ERR_COOKIE_MISMATCH:
_logger.debug("Mismatching cookie received; aborting handshake")
raise
elif err.errqueue and err.errqueue[0][0] == ERR_NO_SHARED_CIPHER:
_logger.debug("No shared cipher; aborting handshake")
raise
_logger.exception("Unexpected error in DTLSv1_listen")
raise
finally:
self._listening = False
self._listening_peer_address = None
if type(peer_address) is tuple:
_logger.debug("New local peer: %s", dtls_peer_address)
self._pending_peer_address = peer_address
else:
self._pending_peer_address = dtls_peer_address
_logger.debug("New peer: %s", self._pending_peer_address)
return self._pending_peer_address | python | def listen(self):
"""Server-side cookie exchange
This method reads datagrams from the socket and initiates cookie
exchange, upon whose successful conclusion one can then proceed to
the accept method. Alternatively, accept can be called directly, in
which case it will call this method. In order to prevent denial-of-
service attacks, only a small, constant set of computing resources
are used during the listen phase.
On some platforms, listen must be called so that packets will be
forwarded to accepted connections. Doing so is therefore recommened
in all cases for portable code.
Return value: a peer address if a datagram from a new peer was
encountered, None if a datagram for a known peer was forwarded
"""
if not hasattr(self, "_listening"):
raise InvalidSocketError("listen called on non-listening socket")
self._pending_peer_address = None
try:
peer_address = self._udp_demux.service()
except socket.timeout:
peer_address = None
except socket.error as sock_err:
if sock_err.errno != errno.EWOULDBLOCK:
_logger.exception("Unexpected socket error in listen")
raise
peer_address = None
if not peer_address:
_logger.debug("Listen returning without peer")
return
# The demux advises that a datagram from a new peer may have arrived
if type(peer_address) is tuple:
# For this type of demux, the write BIO must be pointed at the peer
BIO_dgram_set_peer(self._wbio.value, peer_address)
self._udp_demux.forward()
self._listening_peer_address = peer_address
self._check_nbio()
self._listening = True
try:
_logger.debug("Invoking DTLSv1_listen for ssl: %d",
self._ssl.raw)
dtls_peer_address = DTLSv1_listen(self._ssl.value)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_WANT_READ:
# This method must be called again to forward the next datagram
_logger.debug("DTLSv1_listen must be resumed")
return
elif err.errqueue and err.errqueue[0][0] == ERR_WRONG_VERSION_NUMBER:
_logger.debug("Wrong version number; aborting handshake")
raise
elif err.errqueue and err.errqueue[0][0] == ERR_COOKIE_MISMATCH:
_logger.debug("Mismatching cookie received; aborting handshake")
raise
elif err.errqueue and err.errqueue[0][0] == ERR_NO_SHARED_CIPHER:
_logger.debug("No shared cipher; aborting handshake")
raise
_logger.exception("Unexpected error in DTLSv1_listen")
raise
finally:
self._listening = False
self._listening_peer_address = None
if type(peer_address) is tuple:
_logger.debug("New local peer: %s", dtls_peer_address)
self._pending_peer_address = peer_address
else:
self._pending_peer_address = dtls_peer_address
_logger.debug("New peer: %s", self._pending_peer_address)
return self._pending_peer_address | [
"def",
"listen",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_listening\"",
")",
":",
"raise",
"InvalidSocketError",
"(",
"\"listen called on non-listening socket\"",
")",
"self",
".",
"_pending_peer_address",
"=",
"None",
"try",
":",
"peer_address",
"=",
"self",
".",
"_udp_demux",
".",
"service",
"(",
")",
"except",
"socket",
".",
"timeout",
":",
"peer_address",
"=",
"None",
"except",
"socket",
".",
"error",
"as",
"sock_err",
":",
"if",
"sock_err",
".",
"errno",
"!=",
"errno",
".",
"EWOULDBLOCK",
":",
"_logger",
".",
"exception",
"(",
"\"Unexpected socket error in listen\"",
")",
"raise",
"peer_address",
"=",
"None",
"if",
"not",
"peer_address",
":",
"_logger",
".",
"debug",
"(",
"\"Listen returning without peer\"",
")",
"return",
"# The demux advises that a datagram from a new peer may have arrived",
"if",
"type",
"(",
"peer_address",
")",
"is",
"tuple",
":",
"# For this type of demux, the write BIO must be pointed at the peer",
"BIO_dgram_set_peer",
"(",
"self",
".",
"_wbio",
".",
"value",
",",
"peer_address",
")",
"self",
".",
"_udp_demux",
".",
"forward",
"(",
")",
"self",
".",
"_listening_peer_address",
"=",
"peer_address",
"self",
".",
"_check_nbio",
"(",
")",
"self",
".",
"_listening",
"=",
"True",
"try",
":",
"_logger",
".",
"debug",
"(",
"\"Invoking DTLSv1_listen for ssl: %d\"",
",",
"self",
".",
"_ssl",
".",
"raw",
")",
"dtls_peer_address",
"=",
"DTLSv1_listen",
"(",
"self",
".",
"_ssl",
".",
"value",
")",
"except",
"openssl_error",
"(",
")",
"as",
"err",
":",
"if",
"err",
".",
"ssl_error",
"==",
"SSL_ERROR_WANT_READ",
":",
"# This method must be called again to forward the next datagram",
"_logger",
".",
"debug",
"(",
"\"DTLSv1_listen must be resumed\"",
")",
"return",
"elif",
"err",
".",
"errqueue",
"and",
"err",
".",
"errqueue",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"ERR_WRONG_VERSION_NUMBER",
":",
"_logger",
".",
"debug",
"(",
"\"Wrong version number; aborting handshake\"",
")",
"raise",
"elif",
"err",
".",
"errqueue",
"and",
"err",
".",
"errqueue",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"ERR_COOKIE_MISMATCH",
":",
"_logger",
".",
"debug",
"(",
"\"Mismatching cookie received; aborting handshake\"",
")",
"raise",
"elif",
"err",
".",
"errqueue",
"and",
"err",
".",
"errqueue",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"ERR_NO_SHARED_CIPHER",
":",
"_logger",
".",
"debug",
"(",
"\"No shared cipher; aborting handshake\"",
")",
"raise",
"_logger",
".",
"exception",
"(",
"\"Unexpected error in DTLSv1_listen\"",
")",
"raise",
"finally",
":",
"self",
".",
"_listening",
"=",
"False",
"self",
".",
"_listening_peer_address",
"=",
"None",
"if",
"type",
"(",
"peer_address",
")",
"is",
"tuple",
":",
"_logger",
".",
"debug",
"(",
"\"New local peer: %s\"",
",",
"dtls_peer_address",
")",
"self",
".",
"_pending_peer_address",
"=",
"peer_address",
"else",
":",
"self",
".",
"_pending_peer_address",
"=",
"dtls_peer_address",
"_logger",
".",
"debug",
"(",
"\"New peer: %s\"",
",",
"self",
".",
"_pending_peer_address",
")",
"return",
"self",
".",
"_pending_peer_address"
] | Server-side cookie exchange
This method reads datagrams from the socket and initiates cookie
exchange, upon whose successful conclusion one can then proceed to
the accept method. Alternatively, accept can be called directly, in
which case it will call this method. In order to prevent denial-of-
service attacks, only a small, constant set of computing resources
are used during the listen phase.
On some platforms, listen must be called so that packets will be
forwarded to accepted connections. Doing so is therefore recommened
in all cases for portable code.
Return value: a peer address if a datagram from a new peer was
encountered, None if a datagram for a known peer was forwarded | [
"Server",
"-",
"side",
"cookie",
"exchange"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L590-L664 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.accept | def accept(self):
"""Server-side UDP connection establishment
This method returns a server-side SSLConnection object, connected to
that peer most recently returned from the listen method and not yet
connected. If there is no such peer, then the listen method is invoked.
Return value: SSLConnection connected to a new peer, None if packet
forwarding only to an existing peer occurred.
"""
if not self._pending_peer_address:
if not self.listen():
_logger.debug("Accept returning without connection")
return
new_conn = SSLConnection(self, self._keyfile, self._certfile, True,
self._cert_reqs, self._ssl_version,
self._ca_certs, self._do_handshake_on_connect,
self._suppress_ragged_eofs, self._ciphers,
cb_user_config_ssl_ctx=self._user_config_ssl_ctx,
cb_user_config_ssl=self._user_config_ssl)
new_peer = self._pending_peer_address
self._pending_peer_address = None
if self._do_handshake_on_connect:
# Note that since that connection's socket was just created in its
# constructor, the following operation must be blocking; hence
# handshake-on-connect can only be used with a routing demux if
# listen is serviced by a separate application thread, or else we
# will hang in this call
new_conn.do_handshake()
_logger.debug("Accept returning new connection for new peer")
return new_conn, new_peer | python | def accept(self):
"""Server-side UDP connection establishment
This method returns a server-side SSLConnection object, connected to
that peer most recently returned from the listen method and not yet
connected. If there is no such peer, then the listen method is invoked.
Return value: SSLConnection connected to a new peer, None if packet
forwarding only to an existing peer occurred.
"""
if not self._pending_peer_address:
if not self.listen():
_logger.debug("Accept returning without connection")
return
new_conn = SSLConnection(self, self._keyfile, self._certfile, True,
self._cert_reqs, self._ssl_version,
self._ca_certs, self._do_handshake_on_connect,
self._suppress_ragged_eofs, self._ciphers,
cb_user_config_ssl_ctx=self._user_config_ssl_ctx,
cb_user_config_ssl=self._user_config_ssl)
new_peer = self._pending_peer_address
self._pending_peer_address = None
if self._do_handshake_on_connect:
# Note that since that connection's socket was just created in its
# constructor, the following operation must be blocking; hence
# handshake-on-connect can only be used with a routing demux if
# listen is serviced by a separate application thread, or else we
# will hang in this call
new_conn.do_handshake()
_logger.debug("Accept returning new connection for new peer")
return new_conn, new_peer | [
"def",
"accept",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pending_peer_address",
":",
"if",
"not",
"self",
".",
"listen",
"(",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Accept returning without connection\"",
")",
"return",
"new_conn",
"=",
"SSLConnection",
"(",
"self",
",",
"self",
".",
"_keyfile",
",",
"self",
".",
"_certfile",
",",
"True",
",",
"self",
".",
"_cert_reqs",
",",
"self",
".",
"_ssl_version",
",",
"self",
".",
"_ca_certs",
",",
"self",
".",
"_do_handshake_on_connect",
",",
"self",
".",
"_suppress_ragged_eofs",
",",
"self",
".",
"_ciphers",
",",
"cb_user_config_ssl_ctx",
"=",
"self",
".",
"_user_config_ssl_ctx",
",",
"cb_user_config_ssl",
"=",
"self",
".",
"_user_config_ssl",
")",
"new_peer",
"=",
"self",
".",
"_pending_peer_address",
"self",
".",
"_pending_peer_address",
"=",
"None",
"if",
"self",
".",
"_do_handshake_on_connect",
":",
"# Note that since that connection's socket was just created in its",
"# constructor, the following operation must be blocking; hence",
"# handshake-on-connect can only be used with a routing demux if",
"# listen is serviced by a separate application thread, or else we",
"# will hang in this call",
"new_conn",
".",
"do_handshake",
"(",
")",
"_logger",
".",
"debug",
"(",
"\"Accept returning new connection for new peer\"",
")",
"return",
"new_conn",
",",
"new_peer"
] | Server-side UDP connection establishment
This method returns a server-side SSLConnection object, connected to
that peer most recently returned from the listen method and not yet
connected. If there is no such peer, then the listen method is invoked.
Return value: SSLConnection connected to a new peer, None if packet
forwarding only to an existing peer occurred. | [
"Server",
"-",
"side",
"UDP",
"connection",
"establishment"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L666-L697 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.connect | def connect(self, peer_address):
"""Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of server peer
"""
self._sock.connect(peer_address)
peer_address = self._sock.getpeername() # substituted host addrinfo
BIO_dgram_set_connected(self._wbio.value, peer_address)
assert self._wbio is self._rbio
if self._do_handshake_on_connect:
self.do_handshake() | python | def connect(self, peer_address):
"""Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of server peer
"""
self._sock.connect(peer_address)
peer_address = self._sock.getpeername() # substituted host addrinfo
BIO_dgram_set_connected(self._wbio.value, peer_address)
assert self._wbio is self._rbio
if self._do_handshake_on_connect:
self.do_handshake() | [
"def",
"connect",
"(",
"self",
",",
"peer_address",
")",
":",
"self",
".",
"_sock",
".",
"connect",
"(",
"peer_address",
")",
"peer_address",
"=",
"self",
".",
"_sock",
".",
"getpeername",
"(",
")",
"# substituted host addrinfo",
"BIO_dgram_set_connected",
"(",
"self",
".",
"_wbio",
".",
"value",
",",
"peer_address",
")",
"assert",
"self",
".",
"_wbio",
"is",
"self",
".",
"_rbio",
"if",
"self",
".",
"_do_handshake_on_connect",
":",
"self",
".",
"do_handshake",
"(",
")"
] | Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of server peer | [
"Client",
"-",
"side",
"UDP",
"connection",
"establishment"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L699-L715 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.do_handshake | def do_handshake(self):
"""Perform a handshake with the peer
This method forces an explicit handshake to be performed with either
the client or server peer.
"""
_logger.debug("Initiating handshake...")
try:
self._wrap_socket_library_call(
lambda: SSL_do_handshake(self._ssl.value),
ERR_HANDSHAKE_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise
self._handshake_done = True
_logger.debug("...completed handshake") | python | def do_handshake(self):
"""Perform a handshake with the peer
This method forces an explicit handshake to be performed with either
the client or server peer.
"""
_logger.debug("Initiating handshake...")
try:
self._wrap_socket_library_call(
lambda: SSL_do_handshake(self._ssl.value),
ERR_HANDSHAKE_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise
self._handshake_done = True
_logger.debug("...completed handshake") | [
"def",
"do_handshake",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Initiating handshake...\"",
")",
"try",
":",
"self",
".",
"_wrap_socket_library_call",
"(",
"lambda",
":",
"SSL_do_handshake",
"(",
"self",
".",
"_ssl",
".",
"value",
")",
",",
"ERR_HANDSHAKE_TIMEOUT",
")",
"except",
"openssl_error",
"(",
")",
"as",
"err",
":",
"if",
"err",
".",
"ssl_error",
"==",
"SSL_ERROR_SYSCALL",
"and",
"err",
".",
"result",
"==",
"-",
"1",
":",
"raise_ssl_error",
"(",
"ERR_PORT_UNREACHABLE",
",",
"err",
")",
"raise",
"self",
".",
"_handshake_done",
"=",
"True",
"_logger",
".",
"debug",
"(",
"\"...completed handshake\"",
")"
] | Perform a handshake with the peer
This method forces an explicit handshake to be performed with either
the client or server peer. | [
"Perform",
"a",
"handshake",
"with",
"the",
"peer"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L717-L734 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.read | def read(self, len=1024, buffer=None):
"""Read data from connection
Read up to len bytes and return them.
Arguments:
len -- maximum number of bytes to read
Return value:
string containing read bytes
"""
try:
return self._wrap_socket_library_call(
lambda: SSL_read(self._ssl.value, len, buffer), ERR_READ_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise | python | def read(self, len=1024, buffer=None):
"""Read data from connection
Read up to len bytes and return them.
Arguments:
len -- maximum number of bytes to read
Return value:
string containing read bytes
"""
try:
return self._wrap_socket_library_call(
lambda: SSL_read(self._ssl.value, len, buffer), ERR_READ_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise | [
"def",
"read",
"(",
"self",
",",
"len",
"=",
"1024",
",",
"buffer",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_wrap_socket_library_call",
"(",
"lambda",
":",
"SSL_read",
"(",
"self",
".",
"_ssl",
".",
"value",
",",
"len",
",",
"buffer",
")",
",",
"ERR_READ_TIMEOUT",
")",
"except",
"openssl_error",
"(",
")",
"as",
"err",
":",
"if",
"err",
".",
"ssl_error",
"==",
"SSL_ERROR_SYSCALL",
"and",
"err",
".",
"result",
"==",
"-",
"1",
":",
"raise_ssl_error",
"(",
"ERR_PORT_UNREACHABLE",
",",
"err",
")",
"raise"
] | Read data from connection
Read up to len bytes and return them.
Arguments:
len -- maximum number of bytes to read
Return value:
string containing read bytes | [
"Read",
"data",
"from",
"connection"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L736-L753 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.write | def write(self, data):
"""Write data to connection
Write data as string of bytes.
Arguments:
data -- buffer containing data to be written
Return value:
number of bytes actually transmitted
"""
try:
ret = self._wrap_socket_library_call(
lambda: SSL_write(self._ssl.value, data), ERR_WRITE_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise
if ret:
self._handshake_done = True
return ret | python | def write(self, data):
"""Write data to connection
Write data as string of bytes.
Arguments:
data -- buffer containing data to be written
Return value:
number of bytes actually transmitted
"""
try:
ret = self._wrap_socket_library_call(
lambda: SSL_write(self._ssl.value, data), ERR_WRITE_TIMEOUT)
except openssl_error() as err:
if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
raise_ssl_error(ERR_PORT_UNREACHABLE, err)
raise
if ret:
self._handshake_done = True
return ret | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"_wrap_socket_library_call",
"(",
"lambda",
":",
"SSL_write",
"(",
"self",
".",
"_ssl",
".",
"value",
",",
"data",
")",
",",
"ERR_WRITE_TIMEOUT",
")",
"except",
"openssl_error",
"(",
")",
"as",
"err",
":",
"if",
"err",
".",
"ssl_error",
"==",
"SSL_ERROR_SYSCALL",
"and",
"err",
".",
"result",
"==",
"-",
"1",
":",
"raise_ssl_error",
"(",
"ERR_PORT_UNREACHABLE",
",",
"err",
")",
"raise",
"if",
"ret",
":",
"self",
".",
"_handshake_done",
"=",
"True",
"return",
"ret"
] | Write data to connection
Write data as string of bytes.
Arguments:
data -- buffer containing data to be written
Return value:
number of bytes actually transmitted | [
"Write",
"data",
"to",
"connection"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L755-L776 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.shutdown | def shutdown(self):
"""Shut down the DTLS connection
This method attemps to complete a bidirectional shutdown between
peers. For non-blocking sockets, it should be called repeatedly until
it no longer raises continuation request exceptions.
"""
if hasattr(self, "_listening"):
# Listening server-side sockets cannot be shut down
return
try:
self._wrap_socket_library_call(
lambda: SSL_shutdown(self._ssl.value), ERR_READ_TIMEOUT)
except openssl_error() as err:
if err.result == 0:
# close-notify alert was just sent; wait for same from peer
# Note: while it might seem wise to suppress further read-aheads
# with SSL_set_read_ahead here, doing so causes a shutdown
# failure (ret: -1, SSL_ERROR_SYSCALL) on the DTLS shutdown
# initiator side. And test_starttls does pass.
self._wrap_socket_library_call(
lambda: SSL_shutdown(self._ssl.value), ERR_READ_TIMEOUT)
else:
raise
if hasattr(self, "_rsock"):
# Return wrapped connected server socket (non-listening)
return _UnwrappedSocket(self._sock, self._rsock, self._udp_demux,
self._ctx,
BIO_dgram_get_peer(self._wbio.value))
# Return unwrapped client-side socket or unwrapped server-side socket
# for single-socket servers
return self._sock | python | def shutdown(self):
"""Shut down the DTLS connection
This method attemps to complete a bidirectional shutdown between
peers. For non-blocking sockets, it should be called repeatedly until
it no longer raises continuation request exceptions.
"""
if hasattr(self, "_listening"):
# Listening server-side sockets cannot be shut down
return
try:
self._wrap_socket_library_call(
lambda: SSL_shutdown(self._ssl.value), ERR_READ_TIMEOUT)
except openssl_error() as err:
if err.result == 0:
# close-notify alert was just sent; wait for same from peer
# Note: while it might seem wise to suppress further read-aheads
# with SSL_set_read_ahead here, doing so causes a shutdown
# failure (ret: -1, SSL_ERROR_SYSCALL) on the DTLS shutdown
# initiator side. And test_starttls does pass.
self._wrap_socket_library_call(
lambda: SSL_shutdown(self._ssl.value), ERR_READ_TIMEOUT)
else:
raise
if hasattr(self, "_rsock"):
# Return wrapped connected server socket (non-listening)
return _UnwrappedSocket(self._sock, self._rsock, self._udp_demux,
self._ctx,
BIO_dgram_get_peer(self._wbio.value))
# Return unwrapped client-side socket or unwrapped server-side socket
# for single-socket servers
return self._sock | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_listening\"",
")",
":",
"# Listening server-side sockets cannot be shut down",
"return",
"try",
":",
"self",
".",
"_wrap_socket_library_call",
"(",
"lambda",
":",
"SSL_shutdown",
"(",
"self",
".",
"_ssl",
".",
"value",
")",
",",
"ERR_READ_TIMEOUT",
")",
"except",
"openssl_error",
"(",
")",
"as",
"err",
":",
"if",
"err",
".",
"result",
"==",
"0",
":",
"# close-notify alert was just sent; wait for same from peer",
"# Note: while it might seem wise to suppress further read-aheads",
"# with SSL_set_read_ahead here, doing so causes a shutdown",
"# failure (ret: -1, SSL_ERROR_SYSCALL) on the DTLS shutdown",
"# initiator side. And test_starttls does pass.",
"self",
".",
"_wrap_socket_library_call",
"(",
"lambda",
":",
"SSL_shutdown",
"(",
"self",
".",
"_ssl",
".",
"value",
")",
",",
"ERR_READ_TIMEOUT",
")",
"else",
":",
"raise",
"if",
"hasattr",
"(",
"self",
",",
"\"_rsock\"",
")",
":",
"# Return wrapped connected server socket (non-listening)",
"return",
"_UnwrappedSocket",
"(",
"self",
".",
"_sock",
",",
"self",
".",
"_rsock",
",",
"self",
".",
"_udp_demux",
",",
"self",
".",
"_ctx",
",",
"BIO_dgram_get_peer",
"(",
"self",
".",
"_wbio",
".",
"value",
")",
")",
"# Return unwrapped client-side socket or unwrapped server-side socket",
"# for single-socket servers",
"return",
"self",
".",
"_sock"
] | Shut down the DTLS connection
This method attemps to complete a bidirectional shutdown between
peers. For non-blocking sockets, it should be called repeatedly until
it no longer raises continuation request exceptions. | [
"Shut",
"down",
"the",
"DTLS",
"connection"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L778-L811 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.getpeercert | def getpeercert(self, binary_form=False):
"""Retrieve the peer's certificate
When binary form is requested, the peer's DER-encoded certficate is
returned if it was transmitted during the handshake.
When binary form is not requested, and the peer's certificate has been
validated, then a certificate dictionary is returned. If the certificate
was not validated, an empty dictionary is returned.
In all cases, None is returned if no certificate was received from the
peer.
"""
try:
peer_cert = _X509(SSL_get_peer_certificate(self._ssl.value))
except openssl_error():
return
if binary_form:
return i2d_X509(peer_cert.value)
if self._cert_reqs == CERT_NONE:
return {}
return decode_cert(peer_cert) | python | def getpeercert(self, binary_form=False):
"""Retrieve the peer's certificate
When binary form is requested, the peer's DER-encoded certficate is
returned if it was transmitted during the handshake.
When binary form is not requested, and the peer's certificate has been
validated, then a certificate dictionary is returned. If the certificate
was not validated, an empty dictionary is returned.
In all cases, None is returned if no certificate was received from the
peer.
"""
try:
peer_cert = _X509(SSL_get_peer_certificate(self._ssl.value))
except openssl_error():
return
if binary_form:
return i2d_X509(peer_cert.value)
if self._cert_reqs == CERT_NONE:
return {}
return decode_cert(peer_cert) | [
"def",
"getpeercert",
"(",
"self",
",",
"binary_form",
"=",
"False",
")",
":",
"try",
":",
"peer_cert",
"=",
"_X509",
"(",
"SSL_get_peer_certificate",
"(",
"self",
".",
"_ssl",
".",
"value",
")",
")",
"except",
"openssl_error",
"(",
")",
":",
"return",
"if",
"binary_form",
":",
"return",
"i2d_X509",
"(",
"peer_cert",
".",
"value",
")",
"if",
"self",
".",
"_cert_reqs",
"==",
"CERT_NONE",
":",
"return",
"{",
"}",
"return",
"decode_cert",
"(",
"peer_cert",
")"
] | Retrieve the peer's certificate
When binary form is requested, the peer's DER-encoded certficate is
returned if it was transmitted during the handshake.
When binary form is not requested, and the peer's certificate has been
validated, then a certificate dictionary is returned. If the certificate
was not validated, an empty dictionary is returned.
In all cases, None is returned if no certificate was received from the
peer. | [
"Retrieve",
"the",
"peer",
"s",
"certificate"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L813-L836 |
rbit/pydtls | dtls/sslconnection.py | SSLConnection.cipher | def cipher(self):
"""Retrieve information about the current cipher
Return a triple consisting of cipher name, SSL protocol version defining
its use, and the number of secret bits. Return None if handshaking
has not been completed.
"""
if not self._handshake_done:
return
current_cipher = SSL_get_current_cipher(self._ssl.value)
cipher_name = SSL_CIPHER_get_name(current_cipher)
cipher_version = SSL_CIPHER_get_version(current_cipher)
cipher_bits = SSL_CIPHER_get_bits(current_cipher)
return cipher_name, cipher_version, cipher_bits | python | def cipher(self):
"""Retrieve information about the current cipher
Return a triple consisting of cipher name, SSL protocol version defining
its use, and the number of secret bits. Return None if handshaking
has not been completed.
"""
if not self._handshake_done:
return
current_cipher = SSL_get_current_cipher(self._ssl.value)
cipher_name = SSL_CIPHER_get_name(current_cipher)
cipher_version = SSL_CIPHER_get_version(current_cipher)
cipher_bits = SSL_CIPHER_get_bits(current_cipher)
return cipher_name, cipher_version, cipher_bits | [
"def",
"cipher",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_handshake_done",
":",
"return",
"current_cipher",
"=",
"SSL_get_current_cipher",
"(",
"self",
".",
"_ssl",
".",
"value",
")",
"cipher_name",
"=",
"SSL_CIPHER_get_name",
"(",
"current_cipher",
")",
"cipher_version",
"=",
"SSL_CIPHER_get_version",
"(",
"current_cipher",
")",
"cipher_bits",
"=",
"SSL_CIPHER_get_bits",
"(",
"current_cipher",
")",
"return",
"cipher_name",
",",
"cipher_version",
",",
"cipher_bits"
] | Retrieve information about the current cipher
Return a triple consisting of cipher name, SSL protocol version defining
its use, and the number of secret bits. Return None if handshaking
has not been completed. | [
"Retrieve",
"information",
"about",
"the",
"current",
"cipher"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L855-L870 |
rbit/pydtls | dtls/__init__.py | _prep_bins | def _prep_bins():
"""
Support for running straight out of a cloned source directory instead
of an installed distribution
"""
from os import path
from sys import platform, maxsize
from shutil import copy
bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86"
package_root = path.abspath(path.dirname(__file__))
prebuilt_path = path.join(package_root, "prebuilt", platform + bit_suffix)
config = {"MANIFEST_DIR": prebuilt_path}
try:
execfile(path.join(prebuilt_path, "manifest.pycfg"), config)
except IOError:
return # there are no prebuilts for this platform - nothing to do
files = map(lambda x: path.join(prebuilt_path, x), config["FILES"])
for prebuilt_file in files:
try:
copy(path.join(prebuilt_path, prebuilt_file), package_root)
except IOError:
pass | python | def _prep_bins():
"""
Support for running straight out of a cloned source directory instead
of an installed distribution
"""
from os import path
from sys import platform, maxsize
from shutil import copy
bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86"
package_root = path.abspath(path.dirname(__file__))
prebuilt_path = path.join(package_root, "prebuilt", platform + bit_suffix)
config = {"MANIFEST_DIR": prebuilt_path}
try:
execfile(path.join(prebuilt_path, "manifest.pycfg"), config)
except IOError:
return # there are no prebuilts for this platform - nothing to do
files = map(lambda x: path.join(prebuilt_path, x), config["FILES"])
for prebuilt_file in files:
try:
copy(path.join(prebuilt_path, prebuilt_file), package_root)
except IOError:
pass | [
"def",
"_prep_bins",
"(",
")",
":",
"from",
"os",
"import",
"path",
"from",
"sys",
"import",
"platform",
",",
"maxsize",
"from",
"shutil",
"import",
"copy",
"bit_suffix",
"=",
"\"-x86_64\"",
"if",
"maxsize",
">",
"2",
"**",
"32",
"else",
"\"-x86\"",
"package_root",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"prebuilt_path",
"=",
"path",
".",
"join",
"(",
"package_root",
",",
"\"prebuilt\"",
",",
"platform",
"+",
"bit_suffix",
")",
"config",
"=",
"{",
"\"MANIFEST_DIR\"",
":",
"prebuilt_path",
"}",
"try",
":",
"execfile",
"(",
"path",
".",
"join",
"(",
"prebuilt_path",
",",
"\"manifest.pycfg\"",
")",
",",
"config",
")",
"except",
"IOError",
":",
"return",
"# there are no prebuilts for this platform - nothing to do",
"files",
"=",
"map",
"(",
"lambda",
"x",
":",
"path",
".",
"join",
"(",
"prebuilt_path",
",",
"x",
")",
",",
"config",
"[",
"\"FILES\"",
"]",
")",
"for",
"prebuilt_file",
"in",
"files",
":",
"try",
":",
"copy",
"(",
"path",
".",
"join",
"(",
"prebuilt_path",
",",
"prebuilt_file",
")",
",",
"package_root",
")",
"except",
"IOError",
":",
"pass"
] | Support for running straight out of a cloned source directory instead
of an installed distribution | [
"Support",
"for",
"running",
"straight",
"out",
"of",
"a",
"cloned",
"source",
"directory",
"instead",
"of",
"an",
"installed",
"distribution"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/__init__.py#L37-L59 |
rbit/pydtls | dtls/demux/osnet.py | UDPDemux.get_connection | def get_connection(self, address):
"""Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance, or the root socket
in case address was None
"""
if not address:
return self._datagram_socket
# Create a new datagram socket bound to the same interface and port as
# the root socket, but connected to the given peer
conn = socket.socket(self._datagram_socket.family,
self._datagram_socket.type,
self._datagram_socket.proto)
conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
conn.bind(self._datagram_socket.getsockname())
conn.connect(address)
_logger.debug("Created new connection for address: %s", address)
return conn | python | def get_connection(self, address):
"""Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance, or the root socket
in case address was None
"""
if not address:
return self._datagram_socket
# Create a new datagram socket bound to the same interface and port as
# the root socket, but connected to the given peer
conn = socket.socket(self._datagram_socket.family,
self._datagram_socket.type,
self._datagram_socket.proto)
conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
conn.bind(self._datagram_socket.getsockname())
conn.connect(address)
_logger.debug("Created new connection for address: %s", address)
return conn | [
"def",
"get_connection",
"(",
"self",
",",
"address",
")",
":",
"if",
"not",
"address",
":",
"return",
"self",
".",
"_datagram_socket",
"# Create a new datagram socket bound to the same interface and port as",
"# the root socket, but connected to the given peer",
"conn",
"=",
"socket",
".",
"socket",
"(",
"self",
".",
"_datagram_socket",
".",
"family",
",",
"self",
".",
"_datagram_socket",
".",
"type",
",",
"self",
".",
"_datagram_socket",
".",
"proto",
")",
"conn",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"conn",
".",
"bind",
"(",
"self",
".",
"_datagram_socket",
".",
"getsockname",
"(",
")",
")",
"conn",
".",
"connect",
"(",
"address",
")",
"_logger",
".",
"debug",
"(",
"\"Created new connection for address: %s\"",
",",
"address",
")",
"return",
"conn"
] | Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance, or the root socket
in case address was None | [
"Create",
"or",
"retrieve",
"a",
"muxed",
"connection"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/demux/osnet.py#L86-L110 |
rbit/pydtls | dtls/openssl.py | SSL_CTX_set_info_callback | def SSL_CTX_set_info_callback(ctx, app_info_cb):
"""
Set the info callback
:param callback: The Python callback to use
:return: None
"""
def py_info_callback(ssl, where, ret):
try:
app_info_cb(SSL(ssl), where, ret)
except:
pass
return
global _info_callback
_info_callback[ctx] = _rvoid_voidp_int_int(py_info_callback)
_SSL_CTX_set_info_callback(ctx, _info_callback[ctx]) | python | def SSL_CTX_set_info_callback(ctx, app_info_cb):
"""
Set the info callback
:param callback: The Python callback to use
:return: None
"""
def py_info_callback(ssl, where, ret):
try:
app_info_cb(SSL(ssl), where, ret)
except:
pass
return
global _info_callback
_info_callback[ctx] = _rvoid_voidp_int_int(py_info_callback)
_SSL_CTX_set_info_callback(ctx, _info_callback[ctx]) | [
"def",
"SSL_CTX_set_info_callback",
"(",
"ctx",
",",
"app_info_cb",
")",
":",
"def",
"py_info_callback",
"(",
"ssl",
",",
"where",
",",
"ret",
")",
":",
"try",
":",
"app_info_cb",
"(",
"SSL",
"(",
"ssl",
")",
",",
"where",
",",
"ret",
")",
"except",
":",
"pass",
"return",
"global",
"_info_callback",
"_info_callback",
"[",
"ctx",
"]",
"=",
"_rvoid_voidp_int_int",
"(",
"py_info_callback",
")",
"_SSL_CTX_set_info_callback",
"(",
"ctx",
",",
"_info_callback",
"[",
"ctx",
"]",
")"
] | Set the info callback
:param callback: The Python callback to use
:return: None | [
"Set",
"the",
"info",
"callback"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/openssl.py#L876-L892 |
rbit/pydtls | dtls/err.py | raise_ssl_error | def raise_ssl_error(code, nested=None):
"""Raise an SSL error with the given error code"""
err_string = str(code) + ": " + _ssl_errors[code]
if nested:
raise SSLError(code, err_string + str(nested))
raise SSLError(code, err_string) | python | def raise_ssl_error(code, nested=None):
"""Raise an SSL error with the given error code"""
err_string = str(code) + ": " + _ssl_errors[code]
if nested:
raise SSLError(code, err_string + str(nested))
raise SSLError(code, err_string) | [
"def",
"raise_ssl_error",
"(",
"code",
",",
"nested",
"=",
"None",
")",
":",
"err_string",
"=",
"str",
"(",
"code",
")",
"+",
"\": \"",
"+",
"_ssl_errors",
"[",
"code",
"]",
"if",
"nested",
":",
"raise",
"SSLError",
"(",
"code",
",",
"err_string",
"+",
"str",
"(",
"nested",
")",
")",
"raise",
"SSLError",
"(",
"code",
",",
"err_string",
")"
] | Raise an SSL error with the given error code | [
"Raise",
"an",
"SSL",
"error",
"with",
"the",
"given",
"error",
"code"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/err.py#L108-L113 |
rbit/pydtls | dtls/demux/router.py | UDPDemux.get_connection | def get_connection(self, address):
"""Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance
"""
if self.connections.has_key(address):
return self.connections[address]
# We need a new datagram socket on a dynamically assigned ephemeral port
conn = socket.socket(self._forwarding_socket.family,
self._forwarding_socket.type,
self._forwarding_socket.proto)
conn.bind((self._forwarding_socket.getsockname()[0], 0))
conn.connect(self._forwarding_socket.getsockname())
if not address:
conn.setblocking(0)
self.connections[address] = conn
_logger.debug("Created new connection for address: %s", address)
return conn | python | def get_connection(self, address):
"""Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance
"""
if self.connections.has_key(address):
return self.connections[address]
# We need a new datagram socket on a dynamically assigned ephemeral port
conn = socket.socket(self._forwarding_socket.family,
self._forwarding_socket.type,
self._forwarding_socket.proto)
conn.bind((self._forwarding_socket.getsockname()[0], 0))
conn.connect(self._forwarding_socket.getsockname())
if not address:
conn.setblocking(0)
self.connections[address] = conn
_logger.debug("Created new connection for address: %s", address)
return conn | [
"def",
"get_connection",
"(",
"self",
",",
"address",
")",
":",
"if",
"self",
".",
"connections",
".",
"has_key",
"(",
"address",
")",
":",
"return",
"self",
".",
"connections",
"[",
"address",
"]",
"# We need a new datagram socket on a dynamically assigned ephemeral port",
"conn",
"=",
"socket",
".",
"socket",
"(",
"self",
".",
"_forwarding_socket",
".",
"family",
",",
"self",
".",
"_forwarding_socket",
".",
"type",
",",
"self",
".",
"_forwarding_socket",
".",
"proto",
")",
"conn",
".",
"bind",
"(",
"(",
"self",
".",
"_forwarding_socket",
".",
"getsockname",
"(",
")",
"[",
"0",
"]",
",",
"0",
")",
")",
"conn",
".",
"connect",
"(",
"self",
".",
"_forwarding_socket",
".",
"getsockname",
"(",
")",
")",
"if",
"not",
"address",
":",
"conn",
".",
"setblocking",
"(",
"0",
")",
"self",
".",
"connections",
"[",
"address",
"]",
"=",
"conn",
"_logger",
".",
"debug",
"(",
"\"Created new connection for address: %s\"",
",",
"address",
")",
"return",
"conn"
] | Create or retrieve a muxed connection
Arguments:
address -- a peer endpoint in IPv4/v6 address format; None refers
to the connection for unknown peers
Return:
a bound, connected datagram socket instance | [
"Create",
"or",
"retrieve",
"a",
"muxed",
"connection"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/demux/router.py#L94-L118 |
rbit/pydtls | dtls/demux/router.py | UDPDemux.service | def service(self):
"""Service the root socket
Read from the root socket and forward one datagram to a
connection. The call will return without forwarding data
if any of the following occurs:
* An error is encountered while reading from the root socket
* Reading from the root socket times out
* The root socket is non-blocking and has no data available
* An empty payload is received
* A non-empty payload is received from an unknown peer (a peer
for which get_connection has not yet been called); in this case,
the payload is held by this instance and will be forwarded when
the forward method is called
Return:
if the datagram received was from a new peer, then the peer's
address; otherwise None
"""
self.payload, self.payload_peer_address = \
self.datagram_socket.recvfrom(UDP_MAX_DGRAM_LENGTH)
_logger.debug("Received datagram from peer: %s",
self.payload_peer_address)
if not self.payload:
self.payload_peer_address = None
return
if self.connections.has_key(self.payload_peer_address):
self.forward()
else:
return self.payload_peer_address | python | def service(self):
"""Service the root socket
Read from the root socket and forward one datagram to a
connection. The call will return without forwarding data
if any of the following occurs:
* An error is encountered while reading from the root socket
* Reading from the root socket times out
* The root socket is non-blocking and has no data available
* An empty payload is received
* A non-empty payload is received from an unknown peer (a peer
for which get_connection has not yet been called); in this case,
the payload is held by this instance and will be forwarded when
the forward method is called
Return:
if the datagram received was from a new peer, then the peer's
address; otherwise None
"""
self.payload, self.payload_peer_address = \
self.datagram_socket.recvfrom(UDP_MAX_DGRAM_LENGTH)
_logger.debug("Received datagram from peer: %s",
self.payload_peer_address)
if not self.payload:
self.payload_peer_address = None
return
if self.connections.has_key(self.payload_peer_address):
self.forward()
else:
return self.payload_peer_address | [
"def",
"service",
"(",
"self",
")",
":",
"self",
".",
"payload",
",",
"self",
".",
"payload_peer_address",
"=",
"self",
".",
"datagram_socket",
".",
"recvfrom",
"(",
"UDP_MAX_DGRAM_LENGTH",
")",
"_logger",
".",
"debug",
"(",
"\"Received datagram from peer: %s\"",
",",
"self",
".",
"payload_peer_address",
")",
"if",
"not",
"self",
".",
"payload",
":",
"self",
".",
"payload_peer_address",
"=",
"None",
"return",
"if",
"self",
".",
"connections",
".",
"has_key",
"(",
"self",
".",
"payload_peer_address",
")",
":",
"self",
".",
"forward",
"(",
")",
"else",
":",
"return",
"self",
".",
"payload_peer_address"
] | Service the root socket
Read from the root socket and forward one datagram to a
connection. The call will return without forwarding data
if any of the following occurs:
* An error is encountered while reading from the root socket
* Reading from the root socket times out
* The root socket is non-blocking and has no data available
* An empty payload is received
* A non-empty payload is received from an unknown peer (a peer
for which get_connection has not yet been called); in this case,
the payload is held by this instance and will be forwarded when
the forward method is called
Return:
if the datagram received was from a new peer, then the peer's
address; otherwise None | [
"Service",
"the",
"root",
"socket"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/demux/router.py#L133-L164 |
rbit/pydtls | dtls/demux/router.py | UDPDemux.forward | def forward(self):
"""Forward a stored datagram
When the service method returns the address of a new peer, it holds
the datagram from that peer in this instance. In this case, this
method will perform the forwarding step. The target connection is the
one associated with address None if get_connection has not been called
since the service method returned the new peer's address, and the
connection associated with the new peer's address if it has.
"""
assert self.payload
assert self.payload_peer_address
if self.connections.has_key(self.payload_peer_address):
conn = self.connections[self.payload_peer_address]
default = False
else:
conn = self.connections[None] # propagate exception if not created
default = True
_logger.debug("Forwarding datagram from peer: %s, default: %s",
self.payload_peer_address, default)
self._forwarding_socket.sendto(self.payload, conn.getsockname())
self.payload = ""
self.payload_peer_address = None | python | def forward(self):
"""Forward a stored datagram
When the service method returns the address of a new peer, it holds
the datagram from that peer in this instance. In this case, this
method will perform the forwarding step. The target connection is the
one associated with address None if get_connection has not been called
since the service method returned the new peer's address, and the
connection associated with the new peer's address if it has.
"""
assert self.payload
assert self.payload_peer_address
if self.connections.has_key(self.payload_peer_address):
conn = self.connections[self.payload_peer_address]
default = False
else:
conn = self.connections[None] # propagate exception if not created
default = True
_logger.debug("Forwarding datagram from peer: %s, default: %s",
self.payload_peer_address, default)
self._forwarding_socket.sendto(self.payload, conn.getsockname())
self.payload = ""
self.payload_peer_address = None | [
"def",
"forward",
"(",
"self",
")",
":",
"assert",
"self",
".",
"payload",
"assert",
"self",
".",
"payload_peer_address",
"if",
"self",
".",
"connections",
".",
"has_key",
"(",
"self",
".",
"payload_peer_address",
")",
":",
"conn",
"=",
"self",
".",
"connections",
"[",
"self",
".",
"payload_peer_address",
"]",
"default",
"=",
"False",
"else",
":",
"conn",
"=",
"self",
".",
"connections",
"[",
"None",
"]",
"# propagate exception if not created",
"default",
"=",
"True",
"_logger",
".",
"debug",
"(",
"\"Forwarding datagram from peer: %s, default: %s\"",
",",
"self",
".",
"payload_peer_address",
",",
"default",
")",
"self",
".",
"_forwarding_socket",
".",
"sendto",
"(",
"self",
".",
"payload",
",",
"conn",
".",
"getsockname",
"(",
")",
")",
"self",
".",
"payload",
"=",
"\"\"",
"self",
".",
"payload_peer_address",
"=",
"None"
] | Forward a stored datagram
When the service method returns the address of a new peer, it holds
the datagram from that peer in this instance. In this case, this
method will perform the forwarding step. The target connection is the
one associated with address None if get_connection has not been called
since the service method returned the new peer's address, and the
connection associated with the new peer's address if it has. | [
"Forward",
"a",
"stored",
"datagram"
] | train | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/demux/router.py#L166-L189 |
glasnt/emojificate | emojificate/templatetags/emojificate.py | emojificate_filter | def emojificate_filter(content, autoescape=True):
"Convert any emoji in a string into accessible content."
# return mark_safe(emojificate(content))
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(emojificate(esc(content))) | python | def emojificate_filter(content, autoescape=True):
"Convert any emoji in a string into accessible content."
# return mark_safe(emojificate(content))
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(emojificate(esc(content))) | [
"def",
"emojificate_filter",
"(",
"content",
",",
"autoescape",
"=",
"True",
")",
":",
"# return mark_safe(emojificate(content))",
"if",
"autoescape",
":",
"esc",
"=",
"conditional_escape",
"else",
":",
"esc",
"=",
"lambda",
"x",
":",
"x",
"return",
"mark_safe",
"(",
"emojificate",
"(",
"esc",
"(",
"content",
")",
")",
")"
] | Convert any emoji in a string into accessible content. | [
"Convert",
"any",
"emoji",
"in",
"a",
"string",
"into",
"accessible",
"content",
"."
] | train | https://github.com/glasnt/emojificate/blob/701baad443022043870389c0e0030ed6b7127448/emojificate/templatetags/emojificate.py#L12-L19 |
xeroc/stakemachine | stakemachine/strategies/walls.py | Walls.updateorders | def updateorders(self):
""" Update the orders
"""
log.info("Replacing orders")
# Canceling orders
self.cancelall()
# Target
target = self.bot.get("target", {})
price = self.getprice()
# prices
buy_price = price * (1 - target["offsets"]["buy"] / 100)
sell_price = price * (1 + target["offsets"]["sell"] / 100)
# Store price in storage for later use
self["feed_price"] = float(price)
# Buy Side
if float(self.balance(self.market["base"])) < buy_price * target["amount"]["buy"]:
InsufficientFundsError(Amount(target["amount"]["buy"] * float(buy_price), self.market["base"]))
self["insufficient_buy"] = True
else:
self["insufficient_buy"] = False
self.market.buy(
buy_price,
Amount(target["amount"]["buy"], self.market["quote"]),
account=self.account
)
# Sell Side
if float(self.balance(self.market["quote"])) < target["amount"]["sell"]:
InsufficientFundsError(Amount(target["amount"]["sell"], self.market["quote"]))
self["insufficient_sell"] = True
else:
self["insufficient_sell"] = False
self.market.sell(
sell_price,
Amount(target["amount"]["sell"], self.market["quote"]),
account=self.account
)
pprint(self.execute()) | python | def updateorders(self):
""" Update the orders
"""
log.info("Replacing orders")
# Canceling orders
self.cancelall()
# Target
target = self.bot.get("target", {})
price = self.getprice()
# prices
buy_price = price * (1 - target["offsets"]["buy"] / 100)
sell_price = price * (1 + target["offsets"]["sell"] / 100)
# Store price in storage for later use
self["feed_price"] = float(price)
# Buy Side
if float(self.balance(self.market["base"])) < buy_price * target["amount"]["buy"]:
InsufficientFundsError(Amount(target["amount"]["buy"] * float(buy_price), self.market["base"]))
self["insufficient_buy"] = True
else:
self["insufficient_buy"] = False
self.market.buy(
buy_price,
Amount(target["amount"]["buy"], self.market["quote"]),
account=self.account
)
# Sell Side
if float(self.balance(self.market["quote"])) < target["amount"]["sell"]:
InsufficientFundsError(Amount(target["amount"]["sell"], self.market["quote"]))
self["insufficient_sell"] = True
else:
self["insufficient_sell"] = False
self.market.sell(
sell_price,
Amount(target["amount"]["sell"], self.market["quote"]),
account=self.account
)
pprint(self.execute()) | [
"def",
"updateorders",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Replacing orders\"",
")",
"# Canceling orders",
"self",
".",
"cancelall",
"(",
")",
"# Target",
"target",
"=",
"self",
".",
"bot",
".",
"get",
"(",
"\"target\"",
",",
"{",
"}",
")",
"price",
"=",
"self",
".",
"getprice",
"(",
")",
"# prices",
"buy_price",
"=",
"price",
"*",
"(",
"1",
"-",
"target",
"[",
"\"offsets\"",
"]",
"[",
"\"buy\"",
"]",
"/",
"100",
")",
"sell_price",
"=",
"price",
"*",
"(",
"1",
"+",
"target",
"[",
"\"offsets\"",
"]",
"[",
"\"sell\"",
"]",
"/",
"100",
")",
"# Store price in storage for later use",
"self",
"[",
"\"feed_price\"",
"]",
"=",
"float",
"(",
"price",
")",
"# Buy Side",
"if",
"float",
"(",
"self",
".",
"balance",
"(",
"self",
".",
"market",
"[",
"\"base\"",
"]",
")",
")",
"<",
"buy_price",
"*",
"target",
"[",
"\"amount\"",
"]",
"[",
"\"buy\"",
"]",
":",
"InsufficientFundsError",
"(",
"Amount",
"(",
"target",
"[",
"\"amount\"",
"]",
"[",
"\"buy\"",
"]",
"*",
"float",
"(",
"buy_price",
")",
",",
"self",
".",
"market",
"[",
"\"base\"",
"]",
")",
")",
"self",
"[",
"\"insufficient_buy\"",
"]",
"=",
"True",
"else",
":",
"self",
"[",
"\"insufficient_buy\"",
"]",
"=",
"False",
"self",
".",
"market",
".",
"buy",
"(",
"buy_price",
",",
"Amount",
"(",
"target",
"[",
"\"amount\"",
"]",
"[",
"\"buy\"",
"]",
",",
"self",
".",
"market",
"[",
"\"quote\"",
"]",
")",
",",
"account",
"=",
"self",
".",
"account",
")",
"# Sell Side",
"if",
"float",
"(",
"self",
".",
"balance",
"(",
"self",
".",
"market",
"[",
"\"quote\"",
"]",
")",
")",
"<",
"target",
"[",
"\"amount\"",
"]",
"[",
"\"sell\"",
"]",
":",
"InsufficientFundsError",
"(",
"Amount",
"(",
"target",
"[",
"\"amount\"",
"]",
"[",
"\"sell\"",
"]",
",",
"self",
".",
"market",
"[",
"\"quote\"",
"]",
")",
")",
"self",
"[",
"\"insufficient_sell\"",
"]",
"=",
"True",
"else",
":",
"self",
"[",
"\"insufficient_sell\"",
"]",
"=",
"False",
"self",
".",
"market",
".",
"sell",
"(",
"sell_price",
",",
"Amount",
"(",
"target",
"[",
"\"amount\"",
"]",
"[",
"\"sell\"",
"]",
",",
"self",
".",
"market",
"[",
"\"quote\"",
"]",
")",
",",
"account",
"=",
"self",
".",
"account",
")",
"pprint",
"(",
"self",
".",
"execute",
"(",
")",
")"
] | Update the orders | [
"Update",
"the",
"orders"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/strategies/walls.py#L35-L78 |
xeroc/stakemachine | stakemachine/strategies/walls.py | Walls.getprice | def getprice(self):
""" Here we obtain the price for the quote and make sure it has
a feed price
"""
target = self.bot.get("target", {})
if target.get("reference") == "feed":
assert self.market == self.market.core_quote_market(), "Wrong market for 'feed' reference!"
ticker = self.market.ticker()
price = ticker.get("quoteSettlement_price")
assert abs(price["price"]) != float("inf"), "Check price feed of asset! (%s)" % str(price)
return price | python | def getprice(self):
""" Here we obtain the price for the quote and make sure it has
a feed price
"""
target = self.bot.get("target", {})
if target.get("reference") == "feed":
assert self.market == self.market.core_quote_market(), "Wrong market for 'feed' reference!"
ticker = self.market.ticker()
price = ticker.get("quoteSettlement_price")
assert abs(price["price"]) != float("inf"), "Check price feed of asset! (%s)" % str(price)
return price | [
"def",
"getprice",
"(",
"self",
")",
":",
"target",
"=",
"self",
".",
"bot",
".",
"get",
"(",
"\"target\"",
",",
"{",
"}",
")",
"if",
"target",
".",
"get",
"(",
"\"reference\"",
")",
"==",
"\"feed\"",
":",
"assert",
"self",
".",
"market",
"==",
"self",
".",
"market",
".",
"core_quote_market",
"(",
")",
",",
"\"Wrong market for 'feed' reference!\"",
"ticker",
"=",
"self",
".",
"market",
".",
"ticker",
"(",
")",
"price",
"=",
"ticker",
".",
"get",
"(",
"\"quoteSettlement_price\"",
")",
"assert",
"abs",
"(",
"price",
"[",
"\"price\"",
"]",
")",
"!=",
"float",
"(",
"\"inf\"",
")",
",",
"\"Check price feed of asset! (%s)\"",
"%",
"str",
"(",
"price",
")",
"return",
"price"
] | Here we obtain the price for the quote and make sure it has
a feed price | [
"Here",
"we",
"obtain",
"the",
"price",
"for",
"the",
"quote",
"and",
"make",
"sure",
"it",
"has",
"a",
"feed",
"price"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/strategies/walls.py#L80-L90 |
xeroc/stakemachine | stakemachine/strategies/walls.py | Walls.tick | def tick(self, d):
""" ticks come in on every block
"""
if self.test_blocks:
if not (self.counter["blocks"] or 0) % self.test_blocks:
self.test()
self.counter["blocks"] += 1 | python | def tick(self, d):
""" ticks come in on every block
"""
if self.test_blocks:
if not (self.counter["blocks"] or 0) % self.test_blocks:
self.test()
self.counter["blocks"] += 1 | [
"def",
"tick",
"(",
"self",
",",
"d",
")",
":",
"if",
"self",
".",
"test_blocks",
":",
"if",
"not",
"(",
"self",
".",
"counter",
"[",
"\"blocks\"",
"]",
"or",
"0",
")",
"%",
"self",
".",
"test_blocks",
":",
"self",
".",
"test",
"(",
")",
"self",
".",
"counter",
"[",
"\"blocks\"",
"]",
"+=",
"1"
] | ticks come in on every block | [
"ticks",
"come",
"in",
"on",
"every",
"block"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/strategies/walls.py#L92-L98 |
xeroc/stakemachine | stakemachine/basestrategy.py | BaseStrategy.orders | def orders(self):
""" Return the bot's open accounts in the current market
"""
self.account.refresh()
return [o for o in self.account.openorders if self.bot["market"] == o.market and self.account.openorders] | python | def orders(self):
""" Return the bot's open accounts in the current market
"""
self.account.refresh()
return [o for o in self.account.openorders if self.bot["market"] == o.market and self.account.openorders] | [
"def",
"orders",
"(",
"self",
")",
":",
"self",
".",
"account",
".",
"refresh",
"(",
")",
"return",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"account",
".",
"openorders",
"if",
"self",
".",
"bot",
"[",
"\"market\"",
"]",
"==",
"o",
".",
"market",
"and",
"self",
".",
"account",
".",
"openorders",
"]"
] | Return the bot's open accounts in the current market | [
"Return",
"the",
"bot",
"s",
"open",
"accounts",
"in",
"the",
"current",
"market"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/basestrategy.py#L116-L120 |
xeroc/stakemachine | stakemachine/basestrategy.py | BaseStrategy._callbackPlaceFillOrders | def _callbackPlaceFillOrders(self, d):
""" This method distringuishes notifications caused by Matched orders
from those caused by placed orders
"""
if isinstance(d, FilledOrder):
self.onOrderMatched(d)
elif isinstance(d, Order):
self.onOrderPlaced(d)
elif isinstance(d, UpdateCallOrder):
self.onUpdateCallOrder(d)
else:
pass | python | def _callbackPlaceFillOrders(self, d):
""" This method distringuishes notifications caused by Matched orders
from those caused by placed orders
"""
if isinstance(d, FilledOrder):
self.onOrderMatched(d)
elif isinstance(d, Order):
self.onOrderPlaced(d)
elif isinstance(d, UpdateCallOrder):
self.onUpdateCallOrder(d)
else:
pass | [
"def",
"_callbackPlaceFillOrders",
"(",
"self",
",",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"FilledOrder",
")",
":",
"self",
".",
"onOrderMatched",
"(",
"d",
")",
"elif",
"isinstance",
"(",
"d",
",",
"Order",
")",
":",
"self",
".",
"onOrderPlaced",
"(",
"d",
")",
"elif",
"isinstance",
"(",
"d",
",",
"UpdateCallOrder",
")",
":",
"self",
".",
"onUpdateCallOrder",
"(",
"d",
")",
"else",
":",
"pass"
] | This method distringuishes notifications caused by Matched orders
from those caused by placed orders | [
"This",
"method",
"distringuishes",
"notifications",
"caused",
"by",
"Matched",
"orders",
"from",
"those",
"caused",
"by",
"placed",
"orders"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/basestrategy.py#L147-L158 |
xeroc/stakemachine | stakemachine/basestrategy.py | BaseStrategy.execute | def execute(self):
""" Execute a bundle of operations
"""
self.bitshares.blocking = "head"
r = self.bitshares.txbuffer.broadcast()
self.bitshares.blocking = False
return r | python | def execute(self):
""" Execute a bundle of operations
"""
self.bitshares.blocking = "head"
r = self.bitshares.txbuffer.broadcast()
self.bitshares.blocking = False
return r | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"bitshares",
".",
"blocking",
"=",
"\"head\"",
"r",
"=",
"self",
".",
"bitshares",
".",
"txbuffer",
".",
"broadcast",
"(",
")",
"self",
".",
"bitshares",
".",
"blocking",
"=",
"False",
"return",
"r"
] | Execute a bundle of operations | [
"Execute",
"a",
"bundle",
"of",
"operations"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/basestrategy.py#L160-L166 |
xeroc/stakemachine | stakemachine/basestrategy.py | BaseStrategy.cancelall | def cancelall(self):
""" Cancel all orders of this bot
"""
if self.orders:
return self.bitshares.cancel(
[o["id"] for o in self.orders],
account=self.account
) | python | def cancelall(self):
""" Cancel all orders of this bot
"""
if self.orders:
return self.bitshares.cancel(
[o["id"] for o in self.orders],
account=self.account
) | [
"def",
"cancelall",
"(",
"self",
")",
":",
"if",
"self",
".",
"orders",
":",
"return",
"self",
".",
"bitshares",
".",
"cancel",
"(",
"[",
"o",
"[",
"\"id\"",
"]",
"for",
"o",
"in",
"self",
".",
"orders",
"]",
",",
"account",
"=",
"self",
".",
"account",
")"
] | Cancel all orders of this bot | [
"Cancel",
"all",
"orders",
"of",
"this",
"bot"
] | train | https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/basestrategy.py#L168-L175 |
erinxocon/requests-xml | requests_xml.py | BaseParser.raw_xml | def raw_xml(self) -> _RawXML:
"""Bytes representation of the XML content.
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return self._xml
else:
return etree.tostring(self.element, encoding='unicode').strip().encode(self.encoding) | python | def raw_xml(self) -> _RawXML:
"""Bytes representation of the XML content.
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return self._xml
else:
return etree.tostring(self.element, encoding='unicode').strip().encode(self.encoding) | [
"def",
"raw_xml",
"(",
"self",
")",
"->",
"_RawXML",
":",
"if",
"self",
".",
"_xml",
":",
"return",
"self",
".",
"_xml",
"else",
":",
"return",
"etree",
".",
"tostring",
"(",
"self",
".",
"element",
",",
"encoding",
"=",
"'unicode'",
")",
".",
"strip",
"(",
")",
".",
"encode",
"(",
"self",
".",
"encoding",
")"
] | Bytes representation of the XML content.
(`learn more <http://www.diveintopython3.net/strings.html>`_). | [
"Bytes",
"representation",
"of",
"the",
"XML",
"content",
".",
"(",
"learn",
"more",
"<http",
":",
"//",
"www",
".",
"diveintopython3",
".",
"net",
"/",
"strings",
".",
"html",
">",
"_",
")",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L72-L79 |
erinxocon/requests-xml | requests_xml.py | BaseParser.xml | def xml(self) -> _BaseXML:
"""Unicode representation of the XML content
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return self.raw_xml.decode(self.encoding)
else:
return etree.tostring(self.element, encoding='unicode').strip() | python | def xml(self) -> _BaseXML:
"""Unicode representation of the XML content
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return self.raw_xml.decode(self.encoding)
else:
return etree.tostring(self.element, encoding='unicode').strip() | [
"def",
"xml",
"(",
"self",
")",
"->",
"_BaseXML",
":",
"if",
"self",
".",
"_xml",
":",
"return",
"self",
".",
"raw_xml",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"else",
":",
"return",
"etree",
".",
"tostring",
"(",
"self",
".",
"element",
",",
"encoding",
"=",
"'unicode'",
")",
".",
"strip",
"(",
")"
] | Unicode representation of the XML content
(`learn more <http://www.diveintopython3.net/strings.html>`_). | [
"Unicode",
"representation",
"of",
"the",
"XML",
"content",
"(",
"learn",
"more",
"<http",
":",
"//",
"www",
".",
"diveintopython3",
".",
"net",
"/",
"strings",
".",
"html",
">",
"_",
")",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L83-L90 |
erinxocon/requests-xml | requests_xml.py | BaseParser.pq | def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if self._pq is None:
self._pq = PyQuery(self.raw_xml)
return self._pq | python | def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if self._pq is None:
self._pq = PyQuery(self.raw_xml)
return self._pq | [
"def",
"pq",
"(",
"self",
")",
"->",
"PyQuery",
":",
"if",
"self",
".",
"_pq",
"is",
"None",
":",
"self",
".",
"_pq",
"=",
"PyQuery",
"(",
"self",
".",
"raw_xml",
")",
"return",
"self",
".",
"_pq"
] | `PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`. | [
"PyQuery",
"<https",
":",
"//",
"pythonhosted",
".",
"org",
"/",
"pyquery",
"/",
">",
"_",
"representation",
"of",
"the",
":",
"class",
":",
"Element",
"<Element",
">",
"or",
":",
"class",
":",
"HTML",
"<HTML",
">",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L105-L112 |
erinxocon/requests-xml | requests_xml.py | BaseParser.lxml | def lxml(self) -> _LXML:
"""`lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`.
"""
if self._lxml is None:
self._lxml = etree.fromstring(self.raw_xml)
return self._lxml | python | def lxml(self) -> _LXML:
"""`lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`.
"""
if self._lxml is None:
self._lxml = etree.fromstring(self.raw_xml)
return self._lxml | [
"def",
"lxml",
"(",
"self",
")",
"->",
"_LXML",
":",
"if",
"self",
".",
"_lxml",
"is",
"None",
":",
"self",
".",
"_lxml",
"=",
"etree",
".",
"fromstring",
"(",
"self",
".",
"raw_xml",
")",
"return",
"self",
".",
"_lxml"
] | `lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`. | [
"lxml",
"<http",
":",
"//",
"lxml",
".",
"de",
">",
"_",
"representation",
"of",
"the",
":",
"class",
":",
"Element",
"<Element",
">",
"or",
":",
"class",
":",
"XML",
"<XML",
">",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L115-L122 |
erinxocon/requests-xml | requests_xml.py | BaseParser.links | def links(self) -> _Links:
"""All found links on page, in as–is form. Only works for Atom feeds."""
return list(set(x.text for x in self.xpath('//link'))) | python | def links(self) -> _Links:
"""All found links on page, in as–is form. Only works for Atom feeds."""
return list(set(x.text for x in self.xpath('//link'))) | [
"def",
"links",
"(",
"self",
")",
"->",
"_Links",
":",
"return",
"list",
"(",
"set",
"(",
"x",
".",
"text",
"for",
"x",
"in",
"self",
".",
"xpath",
"(",
"'//link'",
")",
")",
")"
] | All found links on page, in as–is form. Only works for Atom feeds. | [
"All",
"found",
"links",
"on",
"page",
"in",
"as–is",
"form",
".",
"Only",
"works",
"for",
"Atom",
"feeds",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L133-L135 |
erinxocon/requests-xml | requests_xml.py | BaseParser.encoding | def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the XML and
:class:`XMLResponse <XMLResponse>` header.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._xml:
self._encoding = html_to_unicode(self.default_encoding, self._xml)[0]
return self._encoding if self._encoding else self.default_encoding | python | def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the XML and
:class:`XMLResponse <XMLResponse>` header.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._xml:
self._encoding = html_to_unicode(self.default_encoding, self._xml)[0]
return self._encoding if self._encoding else self.default_encoding | [
"def",
"encoding",
"(",
"self",
")",
"->",
"_Encoding",
":",
"if",
"self",
".",
"_encoding",
":",
"return",
"self",
".",
"_encoding",
"# Scan meta tags for charset.",
"if",
"self",
".",
"_xml",
":",
"self",
".",
"_encoding",
"=",
"html_to_unicode",
"(",
"self",
".",
"default_encoding",
",",
"self",
".",
"_xml",
")",
"[",
"0",
"]",
"return",
"self",
".",
"_encoding",
"if",
"self",
".",
"_encoding",
"else",
"self",
".",
"default_encoding"
] | The encoding string to be used, extracted from the XML and
:class:`XMLResponse <XMLResponse>` header. | [
"The",
"encoding",
"string",
"to",
"be",
"used",
"extracted",
"from",
"the",
"XML",
"and",
":",
"class",
":",
"XMLResponse",
"<XMLResponse",
">",
"header",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L157-L168 |
erinxocon/requests-xml | requests_xml.py | BaseParser.json | def json(self, conversion: _Text = 'badgerfish') -> Mapping:
"""A JSON Representation of the XML. Default is badgerfish.
:param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_)
"""
if not self._json:
if conversion is 'badgerfish':
from xmljson import badgerfish as serializer
elif conversion is 'abdera':
from xmljson import abdera as serializer
elif conversion is 'cobra':
from xmljson import cobra as serializer
elif conversion is 'gdata':
from xmljson import gdata as serializer
elif conversion is 'parker':
from xmljson import parker as serializer
elif conversion is 'yahoo':
from xmljson import yahoo as serializer
self._json = json.dumps(serializer.data(etree.fromstring(self.xml)))
return self._json | python | def json(self, conversion: _Text = 'badgerfish') -> Mapping:
"""A JSON Representation of the XML. Default is badgerfish.
:param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_)
"""
if not self._json:
if conversion is 'badgerfish':
from xmljson import badgerfish as serializer
elif conversion is 'abdera':
from xmljson import abdera as serializer
elif conversion is 'cobra':
from xmljson import cobra as serializer
elif conversion is 'gdata':
from xmljson import gdata as serializer
elif conversion is 'parker':
from xmljson import parker as serializer
elif conversion is 'yahoo':
from xmljson import yahoo as serializer
self._json = json.dumps(serializer.data(etree.fromstring(self.xml)))
return self._json | [
"def",
"json",
"(",
"self",
",",
"conversion",
":",
"_Text",
"=",
"'badgerfish'",
")",
"->",
"Mapping",
":",
"if",
"not",
"self",
".",
"_json",
":",
"if",
"conversion",
"is",
"'badgerfish'",
":",
"from",
"xmljson",
"import",
"badgerfish",
"as",
"serializer",
"elif",
"conversion",
"is",
"'abdera'",
":",
"from",
"xmljson",
"import",
"abdera",
"as",
"serializer",
"elif",
"conversion",
"is",
"'cobra'",
":",
"from",
"xmljson",
"import",
"cobra",
"as",
"serializer",
"elif",
"conversion",
"is",
"'gdata'",
":",
"from",
"xmljson",
"import",
"gdata",
"as",
"serializer",
"elif",
"conversion",
"is",
"'parker'",
":",
"from",
"xmljson",
"import",
"parker",
"as",
"serializer",
"elif",
"conversion",
"is",
"'yahoo'",
":",
"from",
"xmljson",
"import",
"yahoo",
"as",
"serializer",
"self",
".",
"_json",
"=",
"json",
".",
"dumps",
"(",
"serializer",
".",
"data",
"(",
"etree",
".",
"fromstring",
"(",
"self",
".",
"xml",
")",
")",
")",
"return",
"self",
".",
"_json"
] | A JSON Representation of the XML. Default is badgerfish.
:param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_) | [
"A",
"JSON",
"Representation",
"of",
"the",
"XML",
".",
"Default",
"is",
"badgerfish",
".",
":",
"param",
"conversion",
":",
"Which",
"conversion",
"method",
"to",
"use",
".",
"(",
"learn",
"more",
"<https",
":",
"//",
"github",
".",
"com",
"/",
"sanand0",
"/",
"xmljson#conventions",
">",
"_",
")"
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L177-L203 |
erinxocon/requests-xml | requests_xml.py | BaseParser.xpath | def xpath(self, selector: str, *, first: bool = False, _encoding: str = None) -> _XPath:
"""Given an XPath selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: XPath Selector to use.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If a sub-selector is specified (e.g. ``//a/@href``), a simple
list of results is returned.
See W3School's `XPath Examples
<https://www.w3schools.com/xml/xpath_examples.asp>`_
for more details.
If ``first`` is ``True``, only returns the first
:class:`Element <Element>` found.
"""
selected = self.lxml.xpath(selector)
elements = [
Element(element=selection, default_encoding=_encoding or self.encoding)
if not isinstance(selection, etree._ElementUnicodeResult) else str(selection)
for selection in selected
]
return _get_first_or_list(elements, first) | python | def xpath(self, selector: str, *, first: bool = False, _encoding: str = None) -> _XPath:
"""Given an XPath selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: XPath Selector to use.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If a sub-selector is specified (e.g. ``//a/@href``), a simple
list of results is returned.
See W3School's `XPath Examples
<https://www.w3schools.com/xml/xpath_examples.asp>`_
for more details.
If ``first`` is ``True``, only returns the first
:class:`Element <Element>` found.
"""
selected = self.lxml.xpath(selector)
elements = [
Element(element=selection, default_encoding=_encoding or self.encoding)
if not isinstance(selection, etree._ElementUnicodeResult) else str(selection)
for selection in selected
]
return _get_first_or_list(elements, first) | [
"def",
"xpath",
"(",
"self",
",",
"selector",
":",
"str",
",",
"*",
",",
"first",
":",
"bool",
"=",
"False",
",",
"_encoding",
":",
"str",
"=",
"None",
")",
"->",
"_XPath",
":",
"selected",
"=",
"self",
".",
"lxml",
".",
"xpath",
"(",
"selector",
")",
"elements",
"=",
"[",
"Element",
"(",
"element",
"=",
"selection",
",",
"default_encoding",
"=",
"_encoding",
"or",
"self",
".",
"encoding",
")",
"if",
"not",
"isinstance",
"(",
"selection",
",",
"etree",
".",
"_ElementUnicodeResult",
")",
"else",
"str",
"(",
"selection",
")",
"for",
"selection",
"in",
"selected",
"]",
"return",
"_get_first_or_list",
"(",
"elements",
",",
"first",
")"
] | Given an XPath selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: XPath Selector to use.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If a sub-selector is specified (e.g. ``//a/@href``), a simple
list of results is returned.
See W3School's `XPath Examples
<https://www.w3schools.com/xml/xpath_examples.asp>`_
for more details.
If ``first`` is ``True``, only returns the first
:class:`Element <Element>` found. | [
"Given",
"an",
"XPath",
"selector",
"returns",
"a",
"list",
"of",
":",
"class",
":",
"Element",
"<Element",
">",
"objects",
"or",
"a",
"single",
"one",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L206-L232 |
erinxocon/requests-xml | requests_xml.py | BaseParser.search | def search(self, template: str, first: bool = False) -> _Result:
"""Search the :class:`Element <Element>` for the given parse
template.
:param template: The Parse template to use.
"""
elements = [r for r in findall(template, self.xml)]
return _get_first_or_list(elements, first) | python | def search(self, template: str, first: bool = False) -> _Result:
"""Search the :class:`Element <Element>` for the given parse
template.
:param template: The Parse template to use.
"""
elements = [r for r in findall(template, self.xml)]
return _get_first_or_list(elements, first) | [
"def",
"search",
"(",
"self",
",",
"template",
":",
"str",
",",
"first",
":",
"bool",
"=",
"False",
")",
"->",
"_Result",
":",
"elements",
"=",
"[",
"r",
"for",
"r",
"in",
"findall",
"(",
"template",
",",
"self",
".",
"xml",
")",
"]",
"return",
"_get_first_or_list",
"(",
"elements",
",",
"first",
")"
] | Search the :class:`Element <Element>` for the given parse
template.
:param template: The Parse template to use. | [
"Search",
"the",
":",
"class",
":",
"Element",
"<Element",
">",
"for",
"the",
"given",
"parse",
"template",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L235-L243 |
erinxocon/requests-xml | requests_xml.py | BaseParser.find | def find(self, selector: str = '*', containing: _Containing = None, first: bool = False, _encoding: str = None) -> _Find:
"""Given a simple element name, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: Element name to find.
:param containing: If specified, only return elements that contain the provided text.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If ``first`` is ``True``, only returns the first
:class:`Element <Element>` found.
"""
# Convert a single containing into a list.
if isinstance(containing, str):
containing = [containing]
encoding = _encoding or self.encoding
elements = [
Element(element=found, default_encoding=encoding)
for found in self.pq(selector)
]
if containing:
elements_copy = elements.copy()
elements = []
for element in elements_copy:
if any([c.lower() in element.text.lower() for c in containing]):
elements.append(element)
elements.reverse()
return _get_first_or_list(elements, first) | python | def find(self, selector: str = '*', containing: _Containing = None, first: bool = False, _encoding: str = None) -> _Find:
"""Given a simple element name, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: Element name to find.
:param containing: If specified, only return elements that contain the provided text.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If ``first`` is ``True``, only returns the first
:class:`Element <Element>` found.
"""
# Convert a single containing into a list.
if isinstance(containing, str):
containing = [containing]
encoding = _encoding or self.encoding
elements = [
Element(element=found, default_encoding=encoding)
for found in self.pq(selector)
]
if containing:
elements_copy = elements.copy()
elements = []
for element in elements_copy:
if any([c.lower() in element.text.lower() for c in containing]):
elements.append(element)
elements.reverse()
return _get_first_or_list(elements, first) | [
"def",
"find",
"(",
"self",
",",
"selector",
":",
"str",
"=",
"'*'",
",",
"containing",
":",
"_Containing",
"=",
"None",
",",
"first",
":",
"bool",
"=",
"False",
",",
"_encoding",
":",
"str",
"=",
"None",
")",
"->",
"_Find",
":",
"# Convert a single containing into a list.",
"if",
"isinstance",
"(",
"containing",
",",
"str",
")",
":",
"containing",
"=",
"[",
"containing",
"]",
"encoding",
"=",
"_encoding",
"or",
"self",
".",
"encoding",
"elements",
"=",
"[",
"Element",
"(",
"element",
"=",
"found",
",",
"default_encoding",
"=",
"encoding",
")",
"for",
"found",
"in",
"self",
".",
"pq",
"(",
"selector",
")",
"]",
"if",
"containing",
":",
"elements_copy",
"=",
"elements",
".",
"copy",
"(",
")",
"elements",
"=",
"[",
"]",
"for",
"element",
"in",
"elements_copy",
":",
"if",
"any",
"(",
"[",
"c",
".",
"lower",
"(",
")",
"in",
"element",
".",
"text",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"containing",
"]",
")",
":",
"elements",
".",
"append",
"(",
"element",
")",
"elements",
".",
"reverse",
"(",
")",
"return",
"_get_first_or_list",
"(",
"elements",
",",
"first",
")"
] | Given a simple element name, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: Element name to find.
:param containing: If specified, only return elements that contain the provided text.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If ``first`` is ``True``, only returns the first
:class:`Element <Element>` found. | [
"Given",
"a",
"simple",
"element",
"name",
"returns",
"a",
"list",
"of",
":",
"class",
":",
"Element",
"<Element",
">",
"objects",
"or",
"a",
"single",
"one",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L246-L279 |
erinxocon/requests-xml | requests_xml.py | XMLSession._handle_response | def _handle_response(response, **kwargs) -> XMLResponse:
"""Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects.
"""
if not response.encoding:
response.encoding = DEFAULT_ENCODING
return response | python | def _handle_response(response, **kwargs) -> XMLResponse:
"""Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects.
"""
if not response.encoding:
response.encoding = DEFAULT_ENCODING
return response | [
"def",
"_handle_response",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
"->",
"XMLResponse",
":",
"if",
"not",
"response",
".",
"encoding",
":",
"response",
".",
"encoding",
"=",
"DEFAULT_ENCODING",
"return",
"response"
] | Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects. | [
"Requests",
"HTTP",
"Response",
"handler",
".",
"Attaches",
".",
"html",
"property",
"to",
"class",
":",
"requests",
".",
"Response",
"<requests",
".",
"Response",
">",
"objects",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L410-L417 |
erinxocon/requests-xml | requests_xml.py | XMLSession.request | def request(self, *args, **kwargs) -> XMLResponse:
"""Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`.
"""
# Convert Request object into HTTPRequest object.
r = super(XMLSession, self).request(*args, **kwargs)
return XMLResponse._from_response(r) | python | def request(self, *args, **kwargs) -> XMLResponse:
"""Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`.
"""
# Convert Request object into HTTPRequest object.
r = super(XMLSession, self).request(*args, **kwargs)
return XMLResponse._from_response(r) | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"XMLResponse",
":",
"# Convert Request object into HTTPRequest object.",
"r",
"=",
"super",
"(",
"XMLSession",
",",
"self",
")",
".",
"request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"XMLResponse",
".",
"_from_response",
"(",
"r",
")"
] | Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`. | [
"Makes",
"an",
"HTTP",
"Request",
"with",
"mocked",
"User–Agent",
"headers",
".",
"Returns",
"a",
"class",
":",
"HTTPResponse",
"<HTTPResponse",
">",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L419-L426 |
erinxocon/requests-xml | requests_xml.py | AsyncXMLSession.response_hook | def response_hook(response, **kwargs) -> XMLResponse:
""" Change response enconding and replace it by a HTMLResponse. """
response.encoding = DEFAULT_ENCODING
return XMLResponse._from_response(response) | python | def response_hook(response, **kwargs) -> XMLResponse:
""" Change response enconding and replace it by a HTMLResponse. """
response.encoding = DEFAULT_ENCODING
return XMLResponse._from_response(response) | [
"def",
"response_hook",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
"->",
"XMLResponse",
":",
"response",
".",
"encoding",
"=",
"DEFAULT_ENCODING",
"return",
"XMLResponse",
".",
"_from_response",
"(",
"response",
")"
] | Change response enconding and replace it by a HTMLResponse. | [
"Change",
"response",
"enconding",
"and",
"replace",
"it",
"by",
"a",
"HTMLResponse",
"."
] | train | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L452-L455 |
itamarst/crochet | examples/scheduling.py | _ExchangeRate.start | def start(self):
"""Start the background process."""
self._lc = LoopingCall(self._download)
# Run immediately, and then every 30 seconds:
self._lc.start(30, now=True) | python | def start(self):
"""Start the background process."""
self._lc = LoopingCall(self._download)
# Run immediately, and then every 30 seconds:
self._lc.start(30, now=True) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_lc",
"=",
"LoopingCall",
"(",
"self",
".",
"_download",
")",
"# Run immediately, and then every 30 seconds:",
"self",
".",
"_lc",
".",
"start",
"(",
"30",
",",
"now",
"=",
"True",
")"
] | Start the background process. | [
"Start",
"the",
"background",
"process",
"."
] | train | https://github.com/itamarst/crochet/blob/ecfc22cefa90f3dfbafa71883c1470e7294f2b6d/examples/scheduling.py#L42-L46 |
itamarst/crochet | examples/scheduling.py | _ExchangeRate._download | def _download(self):
"""Download the page."""
print("Downloading!")
def parse(result):
print("Got %r back from Yahoo." % (result,))
values = result.strip().split(",")
self._value = float(values[1])
d = getPage(
"http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=%s=X"
% (self._name,))
d.addCallback(parse)
d.addErrback(log.err)
return d | python | def _download(self):
"""Download the page."""
print("Downloading!")
def parse(result):
print("Got %r back from Yahoo." % (result,))
values = result.strip().split(",")
self._value = float(values[1])
d = getPage(
"http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=%s=X"
% (self._name,))
d.addCallback(parse)
d.addErrback(log.err)
return d | [
"def",
"_download",
"(",
"self",
")",
":",
"print",
"(",
"\"Downloading!\"",
")",
"def",
"parse",
"(",
"result",
")",
":",
"print",
"(",
"\"Got %r back from Yahoo.\"",
"%",
"(",
"result",
",",
")",
")",
"values",
"=",
"result",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"self",
".",
"_value",
"=",
"float",
"(",
"values",
"[",
"1",
"]",
")",
"d",
"=",
"getPage",
"(",
"\"http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=%s=X\"",
"%",
"(",
"self",
".",
"_name",
",",
")",
")",
"d",
".",
"addCallback",
"(",
"parse",
")",
"d",
".",
"addErrback",
"(",
"log",
".",
"err",
")",
"return",
"d"
] | Download the page. | [
"Download",
"the",
"page",
"."
] | train | https://github.com/itamarst/crochet/blob/ecfc22cefa90f3dfbafa71883c1470e7294f2b6d/examples/scheduling.py#L48-L60 |
itamarst/crochet | crochet/_eventloop.py | ResultRegistry.register | def register(self, result):
"""
Register an EventualResult.
May be called in any thread.
"""
if self._stopped:
raise ReactorStopped()
self._results.add(result) | python | def register(self, result):
"""
Register an EventualResult.
May be called in any thread.
"""
if self._stopped:
raise ReactorStopped()
self._results.add(result) | [
"def",
"register",
"(",
"self",
",",
"result",
")",
":",
"if",
"self",
".",
"_stopped",
":",
"raise",
"ReactorStopped",
"(",
")",
"self",
".",
"_results",
".",
"add",
"(",
"result",
")"
] | Register an EventualResult.
May be called in any thread. | [
"Register",
"an",
"EventualResult",
"."
] | train | https://github.com/itamarst/crochet/blob/ecfc22cefa90f3dfbafa71883c1470e7294f2b6d/crochet/_eventloop.py#L80-L88 |
itamarst/crochet | crochet/_eventloop.py | ResultRegistry.stop | def stop(self):
"""
Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be called in the reactor thread.
"""
self._stopped = True
for result in self._results:
result._set_result(Failure(ReactorStopped())) | python | def stop(self):
"""
Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be called in the reactor thread.
"""
self._stopped = True
for result in self._results:
result._set_result(Failure(ReactorStopped())) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_stopped",
"=",
"True",
"for",
"result",
"in",
"self",
".",
"_results",
":",
"result",
".",
"_set_result",
"(",
"Failure",
"(",
"ReactorStopped",
"(",
")",
")",
")"
] | Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be called in the reactor thread. | [
"Indicate",
"no",
"more",
"results",
"will",
"get",
"pushed",
"into",
"EventualResults",
"since",
"the",
"reactor",
"has",
"stopped",
"."
] | train | https://github.com/itamarst/crochet/blob/ecfc22cefa90f3dfbafa71883c1470e7294f2b6d/crochet/_eventloop.py#L91-L100 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.