hexsha
stringlengths
40
40
repo
stringlengths
5
114
path
stringlengths
4
295
license
listlengths
1
10
language
stringclasses
5 values
identifier
stringlengths
1
116
original_docstring
stringlengths
133
7.85k
docstring
stringlengths
7
2.1k
docstring_tokens
listlengths
3
399
code
stringlengths
350
22.6k
code_tokens
listlengths
20
3.22k
short_docstring
stringlengths
0
1.32k
short_docstring_tokens
listlengths
0
359
comment
listlengths
0
1.22k
parameters
listlengths
0
13
docstring_params
dict
has_error
bool
1 class
ast_depth
int64
13
29
code_length
int64
151
3k
original_docstring_length
int64
76
449
f2316b4af3bfddecbf6c629a97bcb68adbc0fac6
paser4se/uimaster
modules/runtime/src/main/java/org/shaolin/bmdp/runtime/ddc/ZookeeperServiceLauncher.java
[ "Apache-2.0" ]
Java
ZookeeperServiceLauncher
/** * Created by lizhiwe on 4/6/2016. * * //zookeeper server node is better be independent from app server. ZookeeperServiceLauncher zkLauncher = new ZookeeperServiceLauncher(false); //custom attributes here zkLauncher.getProperties().setProperty(ZookeeperServiceLauncher.CLIENT_PORT,"2182"); zkLauncher.getProperties().setProperty(ZookeeperServiceLauncher.DATADIR, "/tmp/zookeeper"); // AppContext.get().registerLifeCycleProvider(zkLauncher); * */
Created by lizhiwe on 4/6/2016. zookeeper server node is better be independent from app server.
[ "Created", "by", "lizhiwe", "on", "4", "/", "6", "/", "2016", ".", "zookeeper", "server", "node", "is", "better", "be", "independent", "from", "app", "server", "." ]
public class ZookeeperServiceLauncher implements IServiceProvider, ILifeCycleProvider, IZookeeperServiceLauncher { // private static final String DEFAULT_CFG = "/opt/uimaster/zkcfg/zookeeper.cfg"; // private String configFileLocation = DEFAULT_CFG; private boolean started = false; private Properties properties = new Properties(); private Logger logger = Logger.getLogger(getClass()); public static final String CLIENT_PORT = "clientPort"; public static final String DATADIR = "dataDir"; private boolean isClusterNode = false; public ZookeeperServiceLauncher() { this(false); } public ZookeeperServiceLauncher(boolean isClusterNode) { super(); this.isClusterNode = isClusterNode; } @Override public void configService() { } /** * Start service. * <p/> * The order controlled by the startOrder. */ @Override public void startService() { if (started) { return; } InputStream in = getClass().getResourceAsStream("default_zookeeper.cfg"); try { properties.load(in); } catch (IOException e) { logger.error("Error loading default properties", e); } final QuorumPeerConfig qCfg = new QuorumPeerConfig(); try { qCfg.parseProperties(properties); } catch (IOException | ConfigException e) { logger.error("Error starting Zookeeper server serivce", e); } if (isClusterNode) { final QuorumPeerMain peer = new QuorumPeerMain(); new Thread(new Runnable() { @Override public void run() { try { peer.runFromConfig(qCfg); started = true; } catch (IOException e) { logger.error("Error starting Zookeeper server serivce", e); } } }).start(); return; } final ZooKeeperServerMain serverMain = new ZooKeeperServerMain(); final ServerConfig cfg = new ServerConfig(); cfg.readFrom(qCfg); new Thread(new Runnable() { @Override public void run() { try { serverMain.runFromConfig(cfg); } catch (IOException e) { logger.error("Error starting Zookeeper server serivce", e); } } }).start(); } /** * Return whether the service stopped gracefully. * * @return true if the service ready to stop. */ @Override public boolean readyToStop() { return false; } /** * Stop service. * <p/> * The stopService should stop the service immediately if the option is STOP. */ @Override public void stopService() { // nothing to do } /** * Notify the service to reload or refresh the data it cached. */ @Override public void reload() { // nothing to do } /** * Indicate the service will be run on which level. By default is 0, which means the highest priority. */ @Override public int getRunLevel() { return 1; } @Override public Class getServiceInterface() { return IZookeeperServiceLauncher.class; } public Properties getProperties() { return properties; } }
[ "public", "class", "ZookeeperServiceLauncher", "implements", "IServiceProvider", ",", "ILifeCycleProvider", ",", "IZookeeperServiceLauncher", "{", "private", "boolean", "started", "=", "false", ";", "private", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "private", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "getClass", "(", ")", ")", ";", "public", "static", "final", "String", "CLIENT_PORT", "=", "\"", "clientPort", "\"", ";", "public", "static", "final", "String", "DATADIR", "=", "\"", "dataDir", "\"", ";", "private", "boolean", "isClusterNode", "=", "false", ";", "public", "ZookeeperServiceLauncher", "(", ")", "{", "this", "(", "false", ")", ";", "}", "public", "ZookeeperServiceLauncher", "(", "boolean", "isClusterNode", ")", "{", "super", "(", ")", ";", "this", ".", "isClusterNode", "=", "isClusterNode", ";", "}", "@", "Override", "public", "void", "configService", "(", ")", "{", "}", "/**\n * Start service.\n * <p/>\n * The order controlled by the startOrder.\n */", "@", "Override", "public", "void", "startService", "(", ")", "{", "if", "(", "started", ")", "{", "return", ";", "}", "InputStream", "in", "=", "getClass", "(", ")", ".", "getResourceAsStream", "(", "\"", "default_zookeeper.cfg", "\"", ")", ";", "try", "{", "properties", ".", "load", "(", "in", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"", "Error loading default properties", "\"", ",", "e", ")", ";", "}", "final", "QuorumPeerConfig", "qCfg", "=", "new", "QuorumPeerConfig", "(", ")", ";", "try", "{", "qCfg", ".", "parseProperties", "(", "properties", ")", ";", "}", "catch", "(", "IOException", "|", "ConfigException", "e", ")", "{", "logger", ".", "error", "(", "\"", "Error starting Zookeeper server serivce", "\"", ",", "e", ")", ";", "}", "if", "(", "isClusterNode", ")", "{", "final", "QuorumPeerMain", "peer", "=", "new", "QuorumPeerMain", "(", ")", ";", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "peer", ".", "runFromConfig", "(", "qCfg", ")", ";", "started", "=", "true", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"", "Error starting Zookeeper server serivce", "\"", ",", "e", ")", ";", "}", "}", "}", ")", ".", "start", "(", ")", ";", "return", ";", "}", "final", "ZooKeeperServerMain", "serverMain", "=", "new", "ZooKeeperServerMain", "(", ")", ";", "final", "ServerConfig", "cfg", "=", "new", "ServerConfig", "(", ")", ";", "cfg", ".", "readFrom", "(", "qCfg", ")", ";", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "serverMain", ".", "runFromConfig", "(", "cfg", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"", "Error starting Zookeeper server serivce", "\"", ",", "e", ")", ";", "}", "}", "}", ")", ".", "start", "(", ")", ";", "}", "/**\n * Return whether the service stopped gracefully.\n *\n * @return true if the service ready to stop.\n */", "@", "Override", "public", "boolean", "readyToStop", "(", ")", "{", "return", "false", ";", "}", "/**\n * Stop service.\n * <p/>\n * The stopService should stop the service immediately if the option is STOP.\n */", "@", "Override", "public", "void", "stopService", "(", ")", "{", "}", "/**\n * Notify the service to reload or refresh the data it cached.\n */", "@", "Override", "public", "void", "reload", "(", ")", "{", "}", "/**\n * Indicate the service will be run on which level. By default is 0, which means the highest priority.\n */", "@", "Override", "public", "int", "getRunLevel", "(", ")", "{", "return", "1", ";", "}", "@", "Override", "public", "Class", "getServiceInterface", "(", ")", "{", "return", "IZookeeperServiceLauncher", ".", "class", ";", "}", "public", "Properties", "getProperties", "(", ")", "{", "return", "properties", ";", "}", "}" ]
Created by lizhiwe on 4/6/2016.
[ "Created", "by", "lizhiwe", "on", "4", "/", "6", "/", "2016", "." ]
[ "// private static final String DEFAULT_CFG = \"/opt/uimaster/zkcfg/zookeeper.cfg\";", "// private String configFileLocation = DEFAULT_CFG;", "// nothing to do", "// nothing to do" ]
[ { "param": "IServiceProvider, ILifeCycleProvider, IZookeeperServiceLauncher", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IServiceProvider, ILifeCycleProvider, IZookeeperServiceLauncher", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
22
706
112
e1152519769bde7affee88b82a9e8814a14e5e25
hanishakoneru/hadoop-ozone
hadoop-ozone/ozonefs/src/main/java/org/apache/hadoop/fs/ozone/FilteredClassLoader.java
[ "Apache-2.0" ]
Java
FilteredClassLoader
/** * Class loader which delegates the loading only for the selected class. * * <p> * By default java classloader delegates first all the class loading to the * parent, and loads the class only if it's not found in the class. * <p> * This simple class loader do the opposit. Everything is loaded with this * class loader without delegation _except_ the few classes which are defined * in the constructor. * <p> * With this method we can use two separated class loader (the original main * classloader and instance of this which loaded separated classes, but the * few selected classes are shared between the two class loaders. * <p> * With this approach it's possible to use any older hadoop version * (main classloader) together with ozonefs (instance of this classloader) as * only the selected classes are selected between the class loaders. */
Class loader which delegates the loading only for the selected class. By default java classloader delegates first all the class loading to the parent, and loads the class only if it's not found in the class. This simple class loader do the opposit. Everything is loaded with this class loader without delegation _except_ the few classes which are defined in the constructor. With this method we can use two separated class loader (the original main classloader and instance of this which loaded separated classes, but the few selected classes are shared between the two class loaders. With this approach it's possible to use any older hadoop version (main classloader) together with ozonefs (instance of this classloader) as only the selected classes are selected between the class loaders.
[ "Class", "loader", "which", "delegates", "the", "loading", "only", "for", "the", "selected", "class", ".", "By", "default", "java", "classloader", "delegates", "first", "all", "the", "class", "loading", "to", "the", "parent", "and", "loads", "the", "class", "only", "if", "it", "'", "s", "not", "found", "in", "the", "class", ".", "This", "simple", "class", "loader", "do", "the", "opposit", ".", "Everything", "is", "loaded", "with", "this", "class", "loader", "without", "delegation", "_except_", "the", "few", "classes", "which", "are", "defined", "in", "the", "constructor", ".", "With", "this", "method", "we", "can", "use", "two", "separated", "class", "loader", "(", "the", "original", "main", "classloader", "and", "instance", "of", "this", "which", "loaded", "separated", "classes", "but", "the", "few", "selected", "classes", "are", "shared", "between", "the", "two", "class", "loaders", ".", "With", "this", "approach", "it", "'", "s", "possible", "to", "use", "any", "older", "hadoop", "version", "(", "main", "classloader", ")", "together", "with", "ozonefs", "(", "instance", "of", "this", "classloader", ")", "as", "only", "the", "selected", "classes", "are", "selected", "between", "the", "class", "loaders", "." ]
public class FilteredClassLoader extends URLClassLoader { private final ClassLoader systemClassLoader; private final ClassLoader delegate; private Set<String> delegatedClasses = new HashSet<>(); public FilteredClassLoader(URL[] urls, ClassLoader parent) { super(urls, null); delegatedClasses.add("org.apache.hadoop.crypto.key.KeyProvider"); delegatedClasses.add("org.apache.hadoop.fs.ozone.OzoneClientAdapter"); delegatedClasses.add("org.apache.hadoop.fs.ozone.FileStatusAdapter"); delegatedClasses.add("org.apache.hadoop.security.token.Token"); delegatedClasses.add("org.apache.hadoop.fs.ozone.BasicKeyInfo"); delegatedClasses.add("org.apache.hadoop.fs.ozone.OzoneFSOutputStream"); delegatedClasses.add("org.apache.hadoop.fs.ozone.OzoneFSStorageStatistics"); delegatedClasses.add("org.apache.hadoop.fs.ozone.Statistic"); delegatedClasses.add("org.apache.hadoop.fs.Seekable"); delegatedClasses.add("org.apache.hadoop.io.Text"); delegatedClasses.add("org.apache.hadoop.fs.Path"); delegatedClasses.add("org.apache.hadoop.fs.BlockLocation"); delegatedClasses.addAll(StringUtils.getTrimmedStringCollection( System.getenv("HADOOP_OZONE_DELEGATED_CLASSES"))); this.delegate = parent; systemClassLoader = getSystemClassLoader(); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (delegatedClasses.contains(name) || name.startsWith("org.apache.log4j") || name.startsWith("org.slf4j")) { return delegate.loadClass(name); } return super.loadClass(name); } private Class<?> loadFromSystem(String name) { if (systemClassLoader != null) { try { return systemClassLoader.loadClass(name); } catch (ClassNotFoundException ex) { //no problem return null; } } else { return null; } } }
[ "public", "class", "FilteredClassLoader", "extends", "URLClassLoader", "{", "private", "final", "ClassLoader", "systemClassLoader", ";", "private", "final", "ClassLoader", "delegate", ";", "private", "Set", "<", "String", ">", "delegatedClasses", "=", "new", "HashSet", "<", ">", "(", ")", ";", "public", "FilteredClassLoader", "(", "URL", "[", "]", "urls", ",", "ClassLoader", "parent", ")", "{", "super", "(", "urls", ",", "null", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.crypto.key.KeyProvider", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.ozone.OzoneClientAdapter", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.ozone.FileStatusAdapter", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.security.token.Token", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.ozone.BasicKeyInfo", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.ozone.OzoneFSOutputStream", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.ozone.OzoneFSStorageStatistics", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.ozone.Statistic", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.Seekable", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.io.Text", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.Path", "\"", ")", ";", "delegatedClasses", ".", "add", "(", "\"", "org.apache.hadoop.fs.BlockLocation", "\"", ")", ";", "delegatedClasses", ".", "addAll", "(", "StringUtils", ".", "getTrimmedStringCollection", "(", "System", ".", "getenv", "(", "\"", "HADOOP_OZONE_DELEGATED_CLASSES", "\"", ")", ")", ")", ";", "this", ".", "delegate", "=", "parent", ";", "systemClassLoader", "=", "getSystemClassLoader", "(", ")", ";", "}", "@", "Override", "public", "Class", "<", "?", ">", "loadClass", "(", "String", "name", ")", "throws", "ClassNotFoundException", "{", "if", "(", "delegatedClasses", ".", "contains", "(", "name", ")", "||", "name", ".", "startsWith", "(", "\"", "org.apache.log4j", "\"", ")", "||", "name", ".", "startsWith", "(", "\"", "org.slf4j", "\"", ")", ")", "{", "return", "delegate", ".", "loadClass", "(", "name", ")", ";", "}", "return", "super", ".", "loadClass", "(", "name", ")", ";", "}", "private", "Class", "<", "?", ">", "loadFromSystem", "(", "String", "name", ")", "{", "if", "(", "systemClassLoader", "!=", "null", ")", "{", "try", "{", "return", "systemClassLoader", ".", "loadClass", "(", "name", ")", ";", "}", "catch", "(", "ClassNotFoundException", "ex", ")", "{", "return", "null", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}", "}" ]
Class loader which delegates the loading only for the selected class.
[ "Class", "loader", "which", "delegates", "the", "loading", "only", "for", "the", "selected", "class", "." ]
[ "//no problem" ]
[ { "param": "URLClassLoader", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "URLClassLoader", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
389
189
db8440316efc6394b8b7a5f1ac3d86b59e0c3add
remo5000/magma
lte/gateway/python/magma/pipelined/qos/qos_rate_limiting.py
[ "BSD-3-Clause" ]
Python
QosQueueMap
Creates/Deletes queues in linux. Using Qdiscs for flow based rate limiting(traffic shaping) of user traffic. Queues are created on an egress interface and flows in OVS are programmed with qid to filter traffic to the queue. Traffic matching a specific flow is filtered to a queue and is rate limited based on configured value. Traffic to flows with no QoS configuration are sent to a default queue and are not rate limited. (subscriber id, rule_num)->qid mapping is used to delete a queue when a flow is removed.
Creates/Deletes queues in linux. Using Qdiscs for flow based rate limiting(traffic shaping) of user traffic. Queues are created on an egress interface and flows in OVS are programmed with qid to filter traffic to the queue. Traffic matching a specific flow is filtered to a queue and is rate limited based on configured value. Traffic to flows with no QoS configuration are sent to a default queue and are not rate limited. (subscriber id, rule_num)->qid mapping is used to delete a queue when a flow is removed.
[ "Creates", "/", "Deletes", "queues", "in", "linux", ".", "Using", "Qdiscs", "for", "flow", "based", "rate", "limiting", "(", "traffic", "shaping", ")", "of", "user", "traffic", ".", "Queues", "are", "created", "on", "an", "egress", "interface", "and", "flows", "in", "OVS", "are", "programmed", "with", "qid", "to", "filter", "traffic", "to", "the", "queue", ".", "Traffic", "matching", "a", "specific", "flow", "is", "filtered", "to", "a", "queue", "and", "is", "rate", "limited", "based", "on", "configured", "value", ".", "Traffic", "to", "flows", "with", "no", "QoS", "configuration", "are", "sent", "to", "a", "default", "queue", "and", "are", "not", "rate", "limited", ".", "(", "subscriber", "id", "rule_num", ")", "-", ">", "qid", "mapping", "is", "used", "to", "delete", "a", "queue", "when", "a", "flow", "is", "removed", "." ]
class QosQueueMap: """ Creates/Deletes queues in linux. Using Qdiscs for flow based rate limiting(traffic shaping) of user traffic. Queues are created on an egress interface and flows in OVS are programmed with qid to filter traffic to the queue. Traffic matching a specific flow is filtered to a queue and is rate limited based on configured value. Traffic to flows with no QoS configuration are sent to a default queue and are not rate limited. (subscriber id, rule_num)->qid mapping is used to delete a queue when a flow is removed. """ def __init__(self, nat_iface: str, enodeb_iface: str, enable_qdisc: bool) -> None: self._uplink = nat_iface self._downlink = enodeb_iface self._enable_qdisc = enable_qdisc # Flag to enable qdisc self._qdisc_initialized = False self._free_qid = 2 self._flow_to_queue = defaultdict(dict) # type: Dict[str, Dict[int, tuple]] self._free_qid_list = deque() # type: deque logging.info("Init QoS Module %s", self._uplink) def map_flow_to_queue(self, imsi: str, rule_num: int, max_bw: int, is_up_link: bool) -> int: """ Creates a queue in linux and adds (imsi, rule_num)->qid mapping Args: imsi: subscriber id rule_num: rule number of the policy (imsi, rule_num) uniquely identify a flow max_bw: max bandwidth on up link is_up_link: Configuration is for uplink or downlink Returns: Queue ID that should be programmed in the flow """ if not self._enable_qdisc: return 0 if not self._qdisc_initialized: TrafficClass.init_qdisc(self._uplink) TrafficClass.init_qdisc(self._downlink) self._qdisc_initialized = True qid = self._create_queue(max_bw, is_up_link) self._flow_to_queue[imsi][rule_num] = (qid, is_up_link) return qid def del_queue_for_flow(self, imsi: str, rule_num: int) -> None: """ Deletes a queue and removes (imsi, rule_num)->qid mapping Delete the flow using the queue before deleting the flow Args: imsi: subscriber id rule_num: rule number of the policy (imsi, rule_num) uniquely identify a flow """ if not self._enable_qdisc: return if imsi in self._flow_to_queue: q = self._flow_to_queue[imsi] qid, is_up_link = q.pop(rule_num, (-1, True)) if qid != -1: self._del_queue(qid, is_up_link) def del_subscriber_queues(self, imsi: str) -> None: """ Deletes all queues of a subscriber and clears (imsi, *)->qid mapping Args: imsi: subscriber id """ if not self._enable_qdisc: return if imsi in self._flow_to_queue: for rule_num in self._flow_to_queue[imsi]: qid, is_up_link = self._flow_to_queue[imsi][rule_num] self._del_queue(qid, is_up_link) del self._flow_to_queue[imsi] def _del_queue(self, qid: int, is_up_link: bool) -> None: if is_up_link: TrafficClass.delete_class(self._uplink, qid) else: TrafficClass.delete_class(self._downlink, qid) self._add_qid_to_free_list(qid) def _create_queue(self, max_bw: int, is_up_link: bool) -> int: qid = self._get_qid() if is_up_link: TrafficClass.create_class(self._uplink, qid, max_bw) else: TrafficClass.create_class(self._downlink, qid, max_bw) return qid def _get_qid(self) -> int: qid = self._get_free_qid() if qid == 0: qid = self._free_qid self._free_qid += 1 return qid def _get_free_qid(self) -> int: if len(self._free_qid_list) != 0: qid = self._free_qid_list.popleft() return qid return 0 def _add_qid_to_free_list(self, qid: int) -> None: self._free_qid_list.append(qid)
[ "class", "QosQueueMap", ":", "def", "__init__", "(", "self", ",", "nat_iface", ":", "str", ",", "enodeb_iface", ":", "str", ",", "enable_qdisc", ":", "bool", ")", "->", "None", ":", "self", ".", "_uplink", "=", "nat_iface", "self", ".", "_downlink", "=", "enodeb_iface", "self", ".", "_enable_qdisc", "=", "enable_qdisc", "self", ".", "_qdisc_initialized", "=", "False", "self", ".", "_free_qid", "=", "2", "self", ".", "_flow_to_queue", "=", "defaultdict", "(", "dict", ")", "self", ".", "_free_qid_list", "=", "deque", "(", ")", "logging", ".", "info", "(", "\"Init QoS Module %s\"", ",", "self", ".", "_uplink", ")", "def", "map_flow_to_queue", "(", "self", ",", "imsi", ":", "str", ",", "rule_num", ":", "int", ",", "max_bw", ":", "int", ",", "is_up_link", ":", "bool", ")", "->", "int", ":", "\"\"\"\n Creates a queue in linux and\n adds (imsi, rule_num)->qid mapping\n\n Args:\n imsi: subscriber id\n rule_num: rule number of the policy\n (imsi, rule_num) uniquely identify a flow\n max_bw: max bandwidth on up link\n is_up_link: Configuration is for uplink or downlink\n\n Returns:\n Queue ID that should be programmed in the flow\n \"\"\"", "if", "not", "self", ".", "_enable_qdisc", ":", "return", "0", "if", "not", "self", ".", "_qdisc_initialized", ":", "TrafficClass", ".", "init_qdisc", "(", "self", ".", "_uplink", ")", "TrafficClass", ".", "init_qdisc", "(", "self", ".", "_downlink", ")", "self", ".", "_qdisc_initialized", "=", "True", "qid", "=", "self", ".", "_create_queue", "(", "max_bw", ",", "is_up_link", ")", "self", ".", "_flow_to_queue", "[", "imsi", "]", "[", "rule_num", "]", "=", "(", "qid", ",", "is_up_link", ")", "return", "qid", "def", "del_queue_for_flow", "(", "self", ",", "imsi", ":", "str", ",", "rule_num", ":", "int", ")", "->", "None", ":", "\"\"\"\n Deletes a queue and removes\n (imsi, rule_num)->qid mapping\n Delete the flow using the queue before deleting the flow\n\n Args:\n imsi: subscriber id\n rule_num: rule number of the policy\n (imsi, rule_num) uniquely identify a flow\n \"\"\"", "if", "not", "self", ".", "_enable_qdisc", ":", "return", "if", "imsi", "in", "self", ".", "_flow_to_queue", ":", "q", "=", "self", ".", "_flow_to_queue", "[", "imsi", "]", "qid", ",", "is_up_link", "=", "q", ".", "pop", "(", "rule_num", ",", "(", "-", "1", ",", "True", ")", ")", "if", "qid", "!=", "-", "1", ":", "self", ".", "_del_queue", "(", "qid", ",", "is_up_link", ")", "def", "del_subscriber_queues", "(", "self", ",", "imsi", ":", "str", ")", "->", "None", ":", "\"\"\"\n Deletes all queues of a subscriber and clears\n (imsi, *)->qid mapping\n\n Args:\n imsi: subscriber id\n \"\"\"", "if", "not", "self", ".", "_enable_qdisc", ":", "return", "if", "imsi", "in", "self", ".", "_flow_to_queue", ":", "for", "rule_num", "in", "self", ".", "_flow_to_queue", "[", "imsi", "]", ":", "qid", ",", "is_up_link", "=", "self", ".", "_flow_to_queue", "[", "imsi", "]", "[", "rule_num", "]", "self", ".", "_del_queue", "(", "qid", ",", "is_up_link", ")", "del", "self", ".", "_flow_to_queue", "[", "imsi", "]", "def", "_del_queue", "(", "self", ",", "qid", ":", "int", ",", "is_up_link", ":", "bool", ")", "->", "None", ":", "if", "is_up_link", ":", "TrafficClass", ".", "delete_class", "(", "self", ".", "_uplink", ",", "qid", ")", "else", ":", "TrafficClass", ".", "delete_class", "(", "self", ".", "_downlink", ",", "qid", ")", "self", ".", "_add_qid_to_free_list", "(", "qid", ")", "def", "_create_queue", "(", "self", ",", "max_bw", ":", "int", ",", "is_up_link", ":", "bool", ")", "->", "int", ":", "qid", "=", "self", ".", "_get_qid", "(", ")", "if", "is_up_link", ":", "TrafficClass", ".", "create_class", "(", "self", ".", "_uplink", ",", "qid", ",", "max_bw", ")", "else", ":", "TrafficClass", ".", "create_class", "(", "self", ".", "_downlink", ",", "qid", ",", "max_bw", ")", "return", "qid", "def", "_get_qid", "(", "self", ")", "->", "int", ":", "qid", "=", "self", ".", "_get_free_qid", "(", ")", "if", "qid", "==", "0", ":", "qid", "=", "self", ".", "_free_qid", "self", ".", "_free_qid", "+=", "1", "return", "qid", "def", "_get_free_qid", "(", "self", ")", "->", "int", ":", "if", "len", "(", "self", ".", "_free_qid_list", ")", "!=", "0", ":", "qid", "=", "self", ".", "_free_qid_list", ".", "popleft", "(", ")", "return", "qid", "return", "0", "def", "_add_qid_to_free_list", "(", "self", ",", "qid", ":", "int", ")", "->", "None", ":", "self", ".", "_free_qid_list", ".", "append", "(", "qid", ")" ]
Creates/Deletes queues in linux.
[ "Creates", "/", "Deletes", "queues", "in", "linux", "." ]
[ "\"\"\"\n Creates/Deletes queues in linux. Using Qdiscs for flow based\n rate limiting(traffic shaping) of user traffic.\n Queues are created on an egress interface and flows\n in OVS are programmed with qid to filter traffic to the queue.\n Traffic matching a specific flow is filtered to a queue and is\n rate limited based on configured value.\n Traffic to flows with no QoS configuration are sent to a\n default queue and are not rate limited.\n\n (subscriber id, rule_num)->qid mapping is used to\n delete a queue when a flow is removed.\n \"\"\"", "# Flag to enable qdisc", "# type: Dict[str, Dict[int, tuple]]", "# type: deque", "\"\"\"\n Creates a queue in linux and\n adds (imsi, rule_num)->qid mapping\n\n Args:\n imsi: subscriber id\n rule_num: rule number of the policy\n (imsi, rule_num) uniquely identify a flow\n max_bw: max bandwidth on up link\n is_up_link: Configuration is for uplink or downlink\n\n Returns:\n Queue ID that should be programmed in the flow\n \"\"\"", "\"\"\"\n Deletes a queue and removes\n (imsi, rule_num)->qid mapping\n Delete the flow using the queue before deleting the flow\n\n Args:\n imsi: subscriber id\n rule_num: rule number of the policy\n (imsi, rule_num) uniquely identify a flow\n \"\"\"", "\"\"\"\n Deletes all queues of a subscriber and clears\n (imsi, *)->qid mapping\n\n Args:\n imsi: subscriber id\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,075
127
9936d28e8389dd00334492c97486fc8f3caad426
juanpablo-rojas/wor-paginate
spec/spy.rb
[ "MIT" ]
Ruby
Spy
# # Class used in tests to keep track of amount of calls for a method in a klass. # # Example in a controller spec: # # before do # Spy.spy(controller, 'authenticate_entity') # perform_some_request # end # # it 'calls authenticate_entity defined by the user' do # count = controller.spied_authenticate_entity_counter # expect(count).to be(1) # end #
Class used in tests to keep track of amount of calls for a method in a klass. Example in a controller spec.
[ "Class", "used", "in", "tests", "to", "keep", "track", "of", "amount", "of", "calls", "for", "a", "method", "in", "a", "klass", ".", "Example", "in", "a", "controller", "spec", "." ]
class Spy # Defines a counter for the given method and overrides it to update # the counter in every call before being executed. def self.spy(klass, method) define_counter(klass, method) klass.singleton_class.class_eval do define_method(method) do |*args, &block| instance_variable_set("@spied_#{method}_counter", instance_variable_get("@spied_#{method}_counter") + 1) super(*args, &block) end end end # Defines a counter (and its getter) for the given method as an instance variable of the given klass. def self.define_counter(klass, method) klass.instance_variable_set("@spied_#{method}_counter".to_sym, 0) klass.singleton_class.class_eval do define_method("spied_#{method}_counter".to_sym) do instance_variable_get("@spied_#{method}_counter") end end end end
[ "class", "Spy", "def", "self", ".", "spy", "(", "klass", ",", "method", ")", "define_counter", "(", "klass", ",", "method", ")", "klass", ".", "singleton_class", ".", "class_eval", "do", "define_method", "(", "method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "instance_variable_set", "(", "\"@spied_#{method}_counter\"", ",", "instance_variable_get", "(", "\"@spied_#{method}_counter\"", ")", "+", "1", ")", "super", "(", "*", "args", ",", "&", "block", ")", "end", "end", "end", "def", "self", ".", "define_counter", "(", "klass", ",", "method", ")", "klass", ".", "instance_variable_set", "(", "\"@spied_#{method}_counter\"", ".", "to_sym", ",", "0", ")", "klass", ".", "singleton_class", ".", "class_eval", "do", "define_method", "(", "\"spied_#{method}_counter\"", ".", "to_sym", ")", "do", "instance_variable_get", "(", "\"@spied_#{method}_counter\"", ")", "end", "end", "end", "end" ]
Class used in tests to keep track of amount of calls for a method in a klass.
[ "Class", "used", "in", "tests", "to", "keep", "track", "of", "amount", "of", "calls", "for", "a", "method", "in", "a", "klass", "." ]
[ "# Defines a counter for the given method and overrides it to update", "# the counter in every call before being executed.", "# Defines a counter (and its getter) for the given method as an instance variable of the given klass." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
206
92
f169fdc214d5a41b6c56e4017bf4a279390381cb
jessepav/beanshell
src/bsh/XThis.java
[ "Apache-2.0" ]
Java
XThis
/** XThis is a dynamically loaded extension which extends This.java and adds support for the generalized interface proxy mechanism introduced in JDK1.3. XThis allows bsh scripted objects to implement arbitrary interfaces (be arbitrary event listener types). Note: This module relies on new features of JDK1.3 and will not compile with JDK1.2 or lower. For those environments simply do not compile this class. Eventually XThis should become simply This, but for backward compatibility we will maintain This without requiring support for the proxy mechanism. XThis stands for "eXtended This" (I had to call it something). @see JThis See also JThis with explicit JFC support for compatibility. @see This */
XThis is a dynamically loaded extension which extends This.java and adds support for the generalized interface proxy mechanism introduced in JDK1.3. XThis allows bsh scripted objects to implement arbitrary interfaces (be arbitrary event listener types). This module relies on new features of JDK1.3 and will not compile with JDK1.2 or lower. For those environments simply do not compile this class. Eventually XThis should become simply This, but for backward compatibility we will maintain This without requiring support for the proxy mechanism. XThis stands for "eXtended This" (I had to call it something).
[ "XThis", "is", "a", "dynamically", "loaded", "extension", "which", "extends", "This", ".", "java", "and", "adds", "support", "for", "the", "generalized", "interface", "proxy", "mechanism", "introduced", "in", "JDK1", ".", "3", ".", "XThis", "allows", "bsh", "scripted", "objects", "to", "implement", "arbitrary", "interfaces", "(", "be", "arbitrary", "event", "listener", "types", ")", ".", "This", "module", "relies", "on", "new", "features", "of", "JDK1", ".", "3", "and", "will", "not", "compile", "with", "JDK1", ".", "2", "or", "lower", ".", "For", "those", "environments", "simply", "do", "not", "compile", "this", "class", ".", "Eventually", "XThis", "should", "become", "simply", "This", "but", "for", "backward", "compatibility", "we", "will", "maintain", "This", "without", "requiring", "support", "for", "the", "proxy", "mechanism", ".", "XThis", "stands", "for", "\"", "eXtended", "This", "\"", "(", "I", "had", "to", "call", "it", "something", ")", "." ]
public class XThis extends This { /** A cache of proxy interface handlers. Currently just one per interface. */ Hashtable interfaces; transient InvocationHandler invocationHandler = new Handler(); public XThis( NameSpace namespace, Interpreter declaringInterp ) { super( namespace, declaringInterp ); } public String toString() { return "'this' reference (XThis) to Bsh object: " + namespace; } /** Get dynamic proxy for interface, caching those it creates. */ public Object getInterface( Class clas ) { return getInterface( new Class[] { clas } ); } /** Get dynamic proxy for interface, caching those it creates. */ public Object getInterface( Class [] ca ) { if ( interfaces == null ) interfaces = new Hashtable(); // Make a hash of the interface hashcodes in order to cache them int hash = 21; for(int i=0; i<ca.length; i++) hash *= ca[i].hashCode() + 3; Object hashKey = new Integer(hash); Object interf = interfaces.get( hashKey ); if ( interf == null ) { ClassLoader classLoader = ca[0].getClassLoader(); // ? interf = Proxy.newProxyInstance( classLoader, ca, invocationHandler ); interfaces.put( hashKey, interf ); } return interf; } /** This is the invocation handler for the dynamic proxy. <p> Notes: Inner class for the invocation handler seems to shield this unavailable interface from JDK1.2 VM... I don't understand this. JThis works just fine even if those classes aren't there (doesn't it?) This class shouldn't be loaded if an XThis isn't instantiated in NameSpace.java, should it? */ class Handler implements InvocationHandler { private Object readResolve() throws ObjectStreamException { throw new NotSerializableException(); } public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { try { return invokeImpl( proxy, method, args ); } catch ( TargetError te ) { // Unwrap target exception. If the interface declares that // it throws the ex it will be delivered. If not it will be // wrapped in an UndeclaredThrowable throw te.getTarget(); } catch ( EvalError ee ) { // Ease debugging... // XThis.this refers to the enclosing class instance if ( Interpreter.DEBUG ) Interpreter.debug( "EvalError in scripted interface: " + XThis.this.toString() + ": "+ ee ); throw ee; } } public Object invokeImpl( Object proxy, Method method, Object[] args ) throws EvalError { String methodName = method.getName(); CallStack callstack = new CallStack( namespace ); /* If equals() is not explicitly defined we must override the default implemented by the This object protocol for scripted object. To support XThis equals() must test for equality with the generated proxy object, not the scripted bsh This object; otherwise callers from outside in Java will not see a the proxy object as equal to itself. */ BshMethod equalsMethod = null; try { equalsMethod = namespace.getMethod( "equals", new Class [] { Object.class } ); } catch ( UtilEvalError e ) {/*leave null*/ } if ( methodName.equals("equals" ) && equalsMethod == null ) { Object obj = args[0]; return proxy == obj ? Boolean.TRUE : Boolean.FALSE; } /* If toString() is not explicitly defined override the default to show the proxy interfaces. */ BshMethod toStringMethod = null; try { toStringMethod = namespace.getMethod( "toString", new Class [] { } ); } catch ( UtilEvalError e ) {/*leave null*/ } if ( methodName.equals("toString" ) && toStringMethod == null) { Class [] ints = proxy.getClass().getInterfaces(); // XThis.this refers to the enclosing class instance StringBuffer sb = new StringBuffer( XThis.this.toString() + "\nimplements:" ); for(int i=0; i<ints.length; i++) sb.append( " "+ ints[i].getName() + ((ints.length > 1)?",":"") ); return sb.toString(); } Class [] paramTypes = method.getParameterTypes(); return Primitive.unwrap( invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) ); } }; }
[ "public", "class", "XThis", "extends", "This", "{", "/**\n\t\tA cache of proxy interface handlers.\n\t\tCurrently just one per interface.\n\t*/", "Hashtable", "interfaces", ";", "transient", "InvocationHandler", "invocationHandler", "=", "new", "Handler", "(", ")", ";", "public", "XThis", "(", "NameSpace", "namespace", ",", "Interpreter", "declaringInterp", ")", "{", "super", "(", "namespace", ",", "declaringInterp", ")", ";", "}", "public", "String", "toString", "(", ")", "{", "return", "\"", "'this' reference (XThis) to Bsh object: ", "\"", "+", "namespace", ";", "}", "/**\n\t\tGet dynamic proxy for interface, caching those it creates.\n\t*/", "public", "Object", "getInterface", "(", "Class", "clas", ")", "{", "return", "getInterface", "(", "new", "Class", "[", "]", "{", "clas", "}", ")", ";", "}", "/**\n\t\tGet dynamic proxy for interface, caching those it creates.\n\t*/", "public", "Object", "getInterface", "(", "Class", "[", "]", "ca", ")", "{", "if", "(", "interfaces", "==", "null", ")", "interfaces", "=", "new", "Hashtable", "(", ")", ";", "int", "hash", "=", "21", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ca", ".", "length", ";", "i", "++", ")", "hash", "*=", "ca", "[", "i", "]", ".", "hashCode", "(", ")", "+", "3", ";", "Object", "hashKey", "=", "new", "Integer", "(", "hash", ")", ";", "Object", "interf", "=", "interfaces", ".", "get", "(", "hashKey", ")", ";", "if", "(", "interf", "==", "null", ")", "{", "ClassLoader", "classLoader", "=", "ca", "[", "0", "]", ".", "getClassLoader", "(", ")", ";", "interf", "=", "Proxy", ".", "newProxyInstance", "(", "classLoader", ",", "ca", ",", "invocationHandler", ")", ";", "interfaces", ".", "put", "(", "hashKey", ",", "interf", ")", ";", "}", "return", "interf", ";", "}", "/**\n\t\tThis is the invocation handler for the dynamic proxy.\n\t\t<p>\n\n\t\tNotes:\n\t\tInner class for the invocation handler seems to shield this unavailable\n\t\tinterface from JDK1.2 VM...\n\n\t\tI don't understand this. JThis works just fine even if those\n\t\tclasses aren't there (doesn't it?) This class shouldn't be loaded\n\t\tif an XThis isn't instantiated in NameSpace.java, should it?\n\t*/", "class", "Handler", "implements", "InvocationHandler", "{", "private", "Object", "readResolve", "(", ")", "throws", "ObjectStreamException", "{", "throw", "new", "NotSerializableException", "(", ")", ";", "}", "public", "Object", "invoke", "(", "Object", "proxy", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "try", "{", "return", "invokeImpl", "(", "proxy", ",", "method", ",", "args", ")", ";", "}", "catch", "(", "TargetError", "te", ")", "{", "throw", "te", ".", "getTarget", "(", ")", ";", "}", "catch", "(", "EvalError", "ee", ")", "{", "if", "(", "Interpreter", ".", "DEBUG", ")", "Interpreter", ".", "debug", "(", "\"", "EvalError in scripted interface: ", "\"", "+", "XThis", ".", "this", ".", "toString", "(", ")", "+", "\"", ": ", "\"", "+", "ee", ")", ";", "throw", "ee", ";", "}", "}", "public", "Object", "invokeImpl", "(", "Object", "proxy", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "EvalError", "{", "String", "methodName", "=", "method", ".", "getName", "(", ")", ";", "CallStack", "callstack", "=", "new", "CallStack", "(", "namespace", ")", ";", "/*\n\t\t\t\tIf equals() is not explicitly defined we must override the\n\t\t\t\tdefault implemented by the This object protocol for scripted\n\t\t\t\tobject. To support XThis equals() must test for equality with\n\t\t\t\tthe generated proxy object, not the scripted bsh This object;\n\t\t\t\totherwise callers from outside in Java will not see a the\n\t\t\t\tproxy object as equal to itself.\n\t\t\t*/", "BshMethod", "equalsMethod", "=", "null", ";", "try", "{", "equalsMethod", "=", "namespace", ".", "getMethod", "(", "\"", "equals", "\"", ",", "new", "Class", "[", "]", "{", "Object", ".", "class", "}", ")", ";", "}", "catch", "(", "UtilEvalError", "e", ")", "{", "/*leave null*/", "}", "if", "(", "methodName", ".", "equals", "(", "\"", "equals", "\"", ")", "&&", "equalsMethod", "==", "null", ")", "{", "Object", "obj", "=", "args", "[", "0", "]", ";", "return", "proxy", "==", "obj", "?", "Boolean", ".", "TRUE", ":", "Boolean", ".", "FALSE", ";", "}", "/*\n\t\t\t\tIf toString() is not explicitly defined override the default\n\t\t\t\tto show the proxy interfaces.\n\t\t\t*/", "BshMethod", "toStringMethod", "=", "null", ";", "try", "{", "toStringMethod", "=", "namespace", ".", "getMethod", "(", "\"", "toString", "\"", ",", "new", "Class", "[", "]", "{", "}", ")", ";", "}", "catch", "(", "UtilEvalError", "e", ")", "{", "/*leave null*/", "}", "if", "(", "methodName", ".", "equals", "(", "\"", "toString", "\"", ")", "&&", "toStringMethod", "==", "null", ")", "{", "Class", "[", "]", "ints", "=", "proxy", ".", "getClass", "(", ")", ".", "getInterfaces", "(", ")", ";", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "XThis", ".", "this", ".", "toString", "(", ")", "+", "\"", "\\n", "implements:", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ints", ".", "length", ";", "i", "++", ")", "sb", ".", "append", "(", "\"", " ", "\"", "+", "ints", "[", "i", "]", ".", "getName", "(", ")", "+", "(", "(", "ints", ".", "length", ">", "1", ")", "?", "\"", ",", "\"", ":", "\"", "\"", ")", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "Class", "[", "]", "paramTypes", "=", "method", ".", "getParameterTypes", "(", ")", ";", "return", "Primitive", ".", "unwrap", "(", "invokeMethod", "(", "methodName", ",", "Primitive", ".", "wrap", "(", "args", ",", "paramTypes", ")", ")", ")", ";", "}", "}", ";", "}" ]
XThis is a dynamically loaded extension which extends This.java and adds support for the generalized interface proxy mechanism introduced in JDK1.3.
[ "XThis", "is", "a", "dynamically", "loaded", "extension", "which", "extends", "This", ".", "java", "and", "adds", "support", "for", "the", "generalized", "interface", "proxy", "mechanism", "introduced", "in", "JDK1", ".", "3", "." ]
[ "// Make a hash of the interface hashcodes in order to cache them", "// ?", "// Unwrap target exception. If the interface declares that", "// it throws the ex it will be delivered. If not it will be", "// wrapped in an UndeclaredThrowable", "// Ease debugging...", "// XThis.this refers to the enclosing class instance", "// XThis.this refers to the enclosing class instance" ]
[ { "param": "This", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "This", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "see", "docstring": "JThis See also JThis with explicit JFC support for compatibility.", "docstring_tokens": [ "JThis", "See", "also", "JThis", "with", "explicit", "JFC", "support", "for", "compatibility", "." ] }, { "identifier": "see", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
19
1,031
162
0d817bde9746ceaed757f467bcb6c8d3450f90b1
SNL-GMS/GMS-PI7-OPEN
gms-common/java/gms/shared/mechanisms/configuration/src/main/java/gms/shared/mechanisms/configuration/constraints/StringConstraint.java
[ "BSD-3-Clause" ]
Java
StringConstraint
/** * A {@link Constraint} with a Set of {@link String} for the value satisfied by a single String. A * StringConstraint can be satisfied in two ways: 1) If the value set contains a single String and * the Operator has {@link Type#EQ} the element is equal to a String from a Selector containing a * single Strubg (or not equal to that String, depending on {@link Operator#isNegated()}. 2) If the * value set contains multiple Strings and the Operator has {@link Type#IN}, determines if the value * set includes a String from a Selector containing a single String (or does not include that * String, depending on {@link Operator#isNegated()}. */
A Constraint with a Set of String for the value satisfied by a single String. A StringConstraint can be satisfied in two ways: 1) If the value set contains a single String and the Operator has Type#EQ the element is equal to a String from a Selector containing a single Strubg (or not equal to that String, depending on Operator#isNegated(). 2) If the value set contains multiple Strings and the Operator has Type#IN, determines if the value set includes a String from a Selector containing a single String (or does not include that String, depending on Operator#isNegated().
[ "A", "Constraint", "with", "a", "Set", "of", "String", "for", "the", "value", "satisfied", "by", "a", "single", "String", ".", "A", "StringConstraint", "can", "be", "satisfied", "in", "two", "ways", ":", "1", ")", "If", "the", "value", "set", "contains", "a", "single", "String", "and", "the", "Operator", "has", "Type#EQ", "the", "element", "is", "equal", "to", "a", "String", "from", "a", "Selector", "containing", "a", "single", "Strubg", "(", "or", "not", "equal", "to", "that", "String", "depending", "on", "Operator#isNegated", "()", ".", "2", ")", "If", "the", "value", "set", "contains", "multiple", "Strings", "and", "the", "Operator", "has", "Type#IN", "determines", "if", "the", "value", "set", "includes", "a", "String", "from", "a", "Selector", "containing", "a", "single", "String", "(", "or", "does", "not", "include", "that", "String", "depending", "on", "Operator#isNegated", "()", "." ]
@AutoValue public abstract class StringConstraint implements Constraint<Set<String>, String> { /** * Obtains a new {@link StringConstraint} with the provided criterion, operator, value, and * priority * * @param criterion String criterion, not null * @param operator {@link Operator}, not null * @param value Set of {@link String}, not null * @param priority priority, larger numbers take precedence over smaller numbers * @return {@link StringConstraint}, not null * @throws NullPointerException if criterion, operator, or value are null * @throws IllegalArgumentException if operator does not have type {@link Type#EQ} or {@link * Type#IN} */ @JsonCreator public static StringConstraint from( @JsonProperty("criterion") String criterion, @JsonProperty("operator") Operator operator, @JsonProperty("value") Set<String> value, @JsonProperty("priority") long priority) { Operator.assertValidOperatorType(operator, Type.IN, Type.EQ); return new AutoValue_StringConstraint(ConstraintType.STRING, criterion, operator, priority, value); } /** * Determines if the {@link String} queryVal satisfies this {@link StringConstraint#getOperator()} * and {@link StringConstraint#getValue()}. 1) If the value set contains a single String and the * Operator has {@link Type#EQ} the element is equal to a String from a Selector containing a * single String (or not equal to that String, depending on {@link Operator#isNegated()}. 2) If * the value set contains multiple String and the Operator has {@link Type#IN}, determines if the * value set includes a String from a Selector containing a single String (or does not include * that String, depending on {@link Operator#isNegated()}. * * @param queryVal {@link String} value, not null * @return true if the queryVal satisfies this PhaseConstraint, and false otherwise * @throws NullPointerException if queryVal is null */ @Override public boolean test(String queryVal) { Objects.requireNonNull(queryVal, "queryVal can't be null"); final Set<String> phases = this.getValue(); if (getOperator().getType() == Type.EQ) { return getOperator().truth(phases.contains(queryVal) && phases.size() == 1); } else if (getOperator().getType() == Type.IN) { return getOperator().truth(phases.contains(queryVal)); } else { return false; } } }
[ "@", "AutoValue", "public", "abstract", "class", "StringConstraint", "implements", "Constraint", "<", "Set", "<", "String", ">", ",", "String", ">", "{", "/**\n * Obtains a new {@link StringConstraint} with the provided criterion, operator, value, and\n * priority\n *\n * @param criterion String criterion, not null\n * @param operator {@link Operator}, not null\n * @param value Set of {@link String}, not null\n * @param priority priority, larger numbers take precedence over smaller numbers\n * @return {@link StringConstraint}, not null\n * @throws NullPointerException if criterion, operator, or value are null\n * @throws IllegalArgumentException if operator does not have type {@link Type#EQ} or {@link\n * Type#IN}\n */", "@", "JsonCreator", "public", "static", "StringConstraint", "from", "(", "@", "JsonProperty", "(", "\"", "criterion", "\"", ")", "String", "criterion", ",", "@", "JsonProperty", "(", "\"", "operator", "\"", ")", "Operator", "operator", ",", "@", "JsonProperty", "(", "\"", "value", "\"", ")", "Set", "<", "String", ">", "value", ",", "@", "JsonProperty", "(", "\"", "priority", "\"", ")", "long", "priority", ")", "{", "Operator", ".", "assertValidOperatorType", "(", "operator", ",", "Type", ".", "IN", ",", "Type", ".", "EQ", ")", ";", "return", "new", "AutoValue_StringConstraint", "(", "ConstraintType", ".", "STRING", ",", "criterion", ",", "operator", ",", "priority", ",", "value", ")", ";", "}", "/**\n * Determines if the {@link String} queryVal satisfies this {@link StringConstraint#getOperator()}\n * and {@link StringConstraint#getValue()}. 1) If the value set contains a single String and the\n * Operator has {@link Type#EQ} the element is equal to a String from a Selector containing a\n * single String (or not equal to that String, depending on {@link Operator#isNegated()}. 2) If\n * the value set contains multiple String and the Operator has {@link Type#IN}, determines if the\n * value set includes a String from a Selector containing a single String (or does not include\n * that String, depending on {@link Operator#isNegated()}.\n *\n * @param queryVal {@link String} value, not null\n * @return true if the queryVal satisfies this PhaseConstraint, and false otherwise\n * @throws NullPointerException if queryVal is null\n */", "@", "Override", "public", "boolean", "test", "(", "String", "queryVal", ")", "{", "Objects", ".", "requireNonNull", "(", "queryVal", ",", "\"", "queryVal can't be null", "\"", ")", ";", "final", "Set", "<", "String", ">", "phases", "=", "this", ".", "getValue", "(", ")", ";", "if", "(", "getOperator", "(", ")", ".", "getType", "(", ")", "==", "Type", ".", "EQ", ")", "{", "return", "getOperator", "(", ")", ".", "truth", "(", "phases", ".", "contains", "(", "queryVal", ")", "&&", "phases", ".", "size", "(", ")", "==", "1", ")", ";", "}", "else", "if", "(", "getOperator", "(", ")", ".", "getType", "(", ")", "==", "Type", ".", "IN", ")", "{", "return", "getOperator", "(", ")", ".", "truth", "(", "phases", ".", "contains", "(", "queryVal", ")", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}" ]
A {@link Constraint} with a Set of {@link String} for the value satisfied by a single String.
[ "A", "{", "@link", "Constraint", "}", "with", "a", "Set", "of", "{", "@link", "String", "}", "for", "the", "value", "satisfied", "by", "a", "single", "String", "." ]
[]
[ { "param": "Constraint<Set<String>, String>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Constraint<Set<String>, String>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
562
157
db16ca01f4992c24f0e473903863ef407a0b0e98
alexanderwendt/acona
src/acona-core/src/main/java/at/tuwien/ict/acona/mq/core/agentfunction/specialfunctions/StateMonitor.java
[ "Apache-2.0" ]
Java
StateMonitor
/** * @author wendt * * Get the state of all functions that are threads in a cell. This functions puts its results in the system state datapoint. At the execution a Json is returned, where each registered function * exists, as well as description and current state [RUNNING, FINISHED, ERROR, INITIALZING] * */
@author wendt Get the state of all functions that are threads in a cell. This functions puts its results in the system state datapoint. At the execution a Json is returned, where each registered function exists, as well as description and current state [RUNNING, FINISHED, ERROR, INITIALZING]
[ "@author", "wendt", "Get", "the", "state", "of", "all", "functions", "that", "are", "threads", "in", "a", "cell", ".", "This", "functions", "puts", "its", "results", "in", "the", "system", "state", "datapoint", ".", "At", "the", "execution", "a", "Json", "is", "returned", "where", "each", "registered", "function", "exists", "as", "well", "as", "description", "and", "current", "state", "[", "RUNNING", "FINISHED", "ERROR", "INITIALZING", "]" ]
public class StateMonitor extends AgentFunctionThreadImpl implements AgentFunctionHandlerListener { private static final Logger log = LoggerFactory.getLogger(StateMonitor.class); public final static String SYSTEMSTATEADDRESS = "systemstate"; private List<String> currentlyRegisteredFunctions = new ArrayList<>(); private Map<String, ServiceState> currentStates = new ConcurrentHashMap<>(); private Map<String, String> currentDescriptions = new ConcurrentHashMap<>(); @Override protected void cellFunctionThreadInit() throws Exception { // Register this function to get notified if new functions are registered or deregistered. this.currentlyRegisteredFunctions = this.getAgent().getFunctionHandler().registerLister(this); this.currentlyRegisteredFunctions.forEach((f) -> { try { this.initializeFunction(f); } catch (Exception e) { log.error("Cannot init state monitor function", e); } }); } @Override protected void executeCustomPreProcessing() throws Exception { // TODO Auto-generated method stub } @Override protected void executeFunction() throws Exception { this.generateSystemState(); } @Override protected void executeCustomPostProcessing() throws Exception { // TODO Auto-generated method stub } @Override protected void updateCustomDatapointsById(String id, JsonElement data) { // log.info("============ Message update ============="); try { log.debug("Received update={}, {}", id, data); Datapoint dp = this.getDatapointBuilder().toDatapoint(data.getAsJsonObject()); ServiceState state = ServiceState.valueOf(dp.getValueAsString()); this.currentStates.put(id, state); this.setStart(); } catch (Exception e) { log.error("Cannot add new system state", e); } log.trace("system state update finished"); } private void generateSystemState() throws Exception { ServiceState agentState = ServiceState.FINISHED; if (this.currentStates.values().contains(ServiceState.ERROR)) { agentState = ServiceState.ERROR; } else if (this.currentStates.values().contains(ServiceState.RUNNING)) { agentState = ServiceState.RUNNING; } Chunk systemState = ChunkBuilder.newChunk("SystemState", "SYSTEMSTATE") .setValue("agentname", this.getAgentName()) .setValue("hasState", agentState.toString()) .setValue("hasDescription", "ACONA Cell"); StringBuilder runningFunctions = new StringBuilder(); this.currentStates.forEach((k, v) -> { try { systemState.addAssociatedContent("hasFunction", ChunkBuilder.newChunk(k, "STATE") .setValue("hasState", v.toString()) .setValue("hasDescription", this.currentDescriptions.get(k))); if (v.equals(ServiceState.RUNNING)) { runningFunctions.append(k + ","); } } catch (Exception e) { log.error("Cannot add state to system state", e); } }); systemState.setValue("runningFunctions", runningFunctions.toString()); this.getCommunicator().write(this.getDatapointBuilder().newDatapoint(SYSTEMSTATEADDRESS).setValue(systemState.toJsonObject())); log.debug("Current system state={}", systemState); } private void initializeFunction(String functionRootAddress) throws Exception { // Add datapoint to managed datapoints this.addManagedDatapoint(DatapointConfig.newConfig(functionRootAddress, functionRootAddress + "/state", SyncMode.SUBSCRIBEONLY)); // Subscribe the datapoint manually from the function to always get the state this.getCommunicator().subscribeDatapoint(functionRootAddress + "/state"); //Datapoint String state = this.getCommunicator().read(functionRootAddress + "/state").getValueOrDefault(new JsonPrimitive(ServiceState.UNDEFINED.toString())).getAsString(); this.currentStates.put(functionRootAddress, ServiceState.valueOf(state)); String description = this.getCommunicator().read(functionRootAddress + "." + AgentFunctionThreadImpl.DESCRIPTIONSUFFIX).getValueOrDefault(new JsonPrimitive("No description available.")).getAsString(); this.currentDescriptions.put(functionRootAddress, description); this.generateSystemState(); // log.info("subscriptions={}", this.getCell().getSubscriptionHandler().getCellFunctionDatapointMapping()); log.debug("Function={}, state={}", functionRootAddress, state); } private void removeFunction(String name) throws Exception { if (this.currentlyRegisteredFunctions.contains(name)) { this.currentlyRegisteredFunctions.remove(name); } this.currentDescriptions.remove(name); this.currentStates.remove(name); this.generateSystemState(); // TODO: Add unsubscribe } @Override protected void shutDownThreadExecutor() throws Exception { // Unregister this function from the function handler listeners this.getAgent().getFunctionHandler().unregisterListener(this); } @Override public void notifyAddedFunction(String registeredFunction) { try { this.initializeFunction(registeredFunction); log.debug("Added function={}", registeredFunction); } catch (Exception e) { log.error("Cannot add cell function", e); } } @Override public void notifyRemovedFunction(String registeredFunction) { try { this.removeFunction(registeredFunction); log.debug("Removed function={}", registeredFunction); } catch (Exception e) { log.error("Cannot remove function", e); } } @Override public String getListenerFunction() { return this.getFunctionRootAddress(); } }
[ "public", "class", "StateMonitor", "extends", "AgentFunctionThreadImpl", "implements", "AgentFunctionHandlerListener", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "StateMonitor", ".", "class", ")", ";", "public", "final", "static", "String", "SYSTEMSTATEADDRESS", "=", "\"", "systemstate", "\"", ";", "private", "List", "<", "String", ">", "currentlyRegisteredFunctions", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "private", "Map", "<", "String", ",", "ServiceState", ">", "currentStates", "=", "new", "ConcurrentHashMap", "<", ">", "(", ")", ";", "private", "Map", "<", "String", ",", "String", ">", "currentDescriptions", "=", "new", "ConcurrentHashMap", "<", ">", "(", ")", ";", "@", "Override", "protected", "void", "cellFunctionThreadInit", "(", ")", "throws", "Exception", "{", "this", ".", "currentlyRegisteredFunctions", "=", "this", ".", "getAgent", "(", ")", ".", "getFunctionHandler", "(", ")", ".", "registerLister", "(", "this", ")", ";", "this", ".", "currentlyRegisteredFunctions", ".", "forEach", "(", "(", "f", ")", "->", "{", "try", "{", "this", ".", "initializeFunction", "(", "f", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Cannot init state monitor function", "\"", ",", "e", ")", ";", "}", "}", ")", ";", "}", "@", "Override", "protected", "void", "executeCustomPreProcessing", "(", ")", "throws", "Exception", "{", "}", "@", "Override", "protected", "void", "executeFunction", "(", ")", "throws", "Exception", "{", "this", ".", "generateSystemState", "(", ")", ";", "}", "@", "Override", "protected", "void", "executeCustomPostProcessing", "(", ")", "throws", "Exception", "{", "}", "@", "Override", "protected", "void", "updateCustomDatapointsById", "(", "String", "id", ",", "JsonElement", "data", ")", "{", "try", "{", "log", ".", "debug", "(", "\"", "Received update={}, {}", "\"", ",", "id", ",", "data", ")", ";", "Datapoint", "dp", "=", "this", ".", "getDatapointBuilder", "(", ")", ".", "toDatapoint", "(", "data", ".", "getAsJsonObject", "(", ")", ")", ";", "ServiceState", "state", "=", "ServiceState", ".", "valueOf", "(", "dp", ".", "getValueAsString", "(", ")", ")", ";", "this", ".", "currentStates", ".", "put", "(", "id", ",", "state", ")", ";", "this", ".", "setStart", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Cannot add new system state", "\"", ",", "e", ")", ";", "}", "log", ".", "trace", "(", "\"", "system state update finished", "\"", ")", ";", "}", "private", "void", "generateSystemState", "(", ")", "throws", "Exception", "{", "ServiceState", "agentState", "=", "ServiceState", ".", "FINISHED", ";", "if", "(", "this", ".", "currentStates", ".", "values", "(", ")", ".", "contains", "(", "ServiceState", ".", "ERROR", ")", ")", "{", "agentState", "=", "ServiceState", ".", "ERROR", ";", "}", "else", "if", "(", "this", ".", "currentStates", ".", "values", "(", ")", ".", "contains", "(", "ServiceState", ".", "RUNNING", ")", ")", "{", "agentState", "=", "ServiceState", ".", "RUNNING", ";", "}", "Chunk", "systemState", "=", "ChunkBuilder", ".", "newChunk", "(", "\"", "SystemState", "\"", ",", "\"", "SYSTEMSTATE", "\"", ")", ".", "setValue", "(", "\"", "agentname", "\"", ",", "this", ".", "getAgentName", "(", ")", ")", ".", "setValue", "(", "\"", "hasState", "\"", ",", "agentState", ".", "toString", "(", ")", ")", ".", "setValue", "(", "\"", "hasDescription", "\"", ",", "\"", "ACONA Cell", "\"", ")", ";", "StringBuilder", "runningFunctions", "=", "new", "StringBuilder", "(", ")", ";", "this", ".", "currentStates", ".", "forEach", "(", "(", "k", ",", "v", ")", "->", "{", "try", "{", "systemState", ".", "addAssociatedContent", "(", "\"", "hasFunction", "\"", ",", "ChunkBuilder", ".", "newChunk", "(", "k", ",", "\"", "STATE", "\"", ")", ".", "setValue", "(", "\"", "hasState", "\"", ",", "v", ".", "toString", "(", ")", ")", ".", "setValue", "(", "\"", "hasDescription", "\"", ",", "this", ".", "currentDescriptions", ".", "get", "(", "k", ")", ")", ")", ";", "if", "(", "v", ".", "equals", "(", "ServiceState", ".", "RUNNING", ")", ")", "{", "runningFunctions", ".", "append", "(", "k", "+", "\"", ",", "\"", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Cannot add state to system state", "\"", ",", "e", ")", ";", "}", "}", ")", ";", "systemState", ".", "setValue", "(", "\"", "runningFunctions", "\"", ",", "runningFunctions", ".", "toString", "(", ")", ")", ";", "this", ".", "getCommunicator", "(", ")", ".", "write", "(", "this", ".", "getDatapointBuilder", "(", ")", ".", "newDatapoint", "(", "SYSTEMSTATEADDRESS", ")", ".", "setValue", "(", "systemState", ".", "toJsonObject", "(", ")", ")", ")", ";", "log", ".", "debug", "(", "\"", "Current system state={}", "\"", ",", "systemState", ")", ";", "}", "private", "void", "initializeFunction", "(", "String", "functionRootAddress", ")", "throws", "Exception", "{", "this", ".", "addManagedDatapoint", "(", "DatapointConfig", ".", "newConfig", "(", "functionRootAddress", ",", "functionRootAddress", "+", "\"", "/state", "\"", ",", "SyncMode", ".", "SUBSCRIBEONLY", ")", ")", ";", "this", ".", "getCommunicator", "(", ")", ".", "subscribeDatapoint", "(", "functionRootAddress", "+", "\"", "/state", "\"", ")", ";", "String", "state", "=", "this", ".", "getCommunicator", "(", ")", ".", "read", "(", "functionRootAddress", "+", "\"", "/state", "\"", ")", ".", "getValueOrDefault", "(", "new", "JsonPrimitive", "(", "ServiceState", ".", "UNDEFINED", ".", "toString", "(", ")", ")", ")", ".", "getAsString", "(", ")", ";", "this", ".", "currentStates", ".", "put", "(", "functionRootAddress", ",", "ServiceState", ".", "valueOf", "(", "state", ")", ")", ";", "String", "description", "=", "this", ".", "getCommunicator", "(", ")", ".", "read", "(", "functionRootAddress", "+", "\"", ".", "\"", "+", "AgentFunctionThreadImpl", ".", "DESCRIPTIONSUFFIX", ")", ".", "getValueOrDefault", "(", "new", "JsonPrimitive", "(", "\"", "No description available.", "\"", ")", ")", ".", "getAsString", "(", ")", ";", "this", ".", "currentDescriptions", ".", "put", "(", "functionRootAddress", ",", "description", ")", ";", "this", ".", "generateSystemState", "(", ")", ";", "log", ".", "debug", "(", "\"", "Function={}, state={}", "\"", ",", "functionRootAddress", ",", "state", ")", ";", "}", "private", "void", "removeFunction", "(", "String", "name", ")", "throws", "Exception", "{", "if", "(", "this", ".", "currentlyRegisteredFunctions", ".", "contains", "(", "name", ")", ")", "{", "this", ".", "currentlyRegisteredFunctions", ".", "remove", "(", "name", ")", ";", "}", "this", ".", "currentDescriptions", ".", "remove", "(", "name", ")", ";", "this", ".", "currentStates", ".", "remove", "(", "name", ")", ";", "this", ".", "generateSystemState", "(", ")", ";", "}", "@", "Override", "protected", "void", "shutDownThreadExecutor", "(", ")", "throws", "Exception", "{", "this", ".", "getAgent", "(", ")", ".", "getFunctionHandler", "(", ")", ".", "unregisterListener", "(", "this", ")", ";", "}", "@", "Override", "public", "void", "notifyAddedFunction", "(", "String", "registeredFunction", ")", "{", "try", "{", "this", ".", "initializeFunction", "(", "registeredFunction", ")", ";", "log", ".", "debug", "(", "\"", "Added function={}", "\"", ",", "registeredFunction", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Cannot add cell function", "\"", ",", "e", ")", ";", "}", "}", "@", "Override", "public", "void", "notifyRemovedFunction", "(", "String", "registeredFunction", ")", "{", "try", "{", "this", ".", "removeFunction", "(", "registeredFunction", ")", ";", "log", ".", "debug", "(", "\"", "Removed function={}", "\"", ",", "registeredFunction", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Cannot remove function", "\"", ",", "e", ")", ";", "}", "}", "@", "Override", "public", "String", "getListenerFunction", "(", ")", "{", "return", "this", ".", "getFunctionRootAddress", "(", ")", ";", "}", "}" ]
@author wendt
[ "@author", "wendt" ]
[ "// Register this function to get notified if new functions are registered or deregistered.", "// TODO Auto-generated method stub", "// TODO Auto-generated method stub", "// log.info(\"============ Message update =============\");", "// Add datapoint to managed datapoints", "// Subscribe the datapoint manually from the function to always get the state", "//Datapoint ", "// log.info(\"subscriptions={}\", this.getCell().getSubscriptionHandler().getCellFunctionDatapointMapping());", "// TODO: Add unsubscribe", "// Unregister this function from the function handler listeners" ]
[ { "param": "AgentFunctionThreadImpl", "type": null }, { "param": "AgentFunctionHandlerListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AgentFunctionThreadImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "AgentFunctionHandlerListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
1,156
76
f21bdcb71f10b6c09a92a9db67fc9c520c0af596
EntitySpaces/EntitySpaces-CompleteSource
EntitySpaces/EntitySpaces.Interfaces/esTransactionScope.cs
[ "Unlicense" ]
C#
esTransactionScope
/// <summary> /// This is the EntitySpaces ADO.NET connection based transaction class that mimics the System.Transactions.TransactionScope class. /// </summary> /// <remarks> /// EntitySpaces supports two transactions models, connection based via this class (esTransactionScope) and the /// new System.Transactions.TransactionScope. Some databases such as Microsoft Access don't support the new System.Transactions.TransactionScope /// class. And still there are other cases where the System.Transactions.TransactionScope class cannot be used as is the case with a lot /// of hosting companies. Thus EntitySpaces provides a very nice ADO.NET connection based transaction handler. /// /// The Syntax should be as follows: /// <code> /// using (esTransactionScope scope = new esTransactionScope()) /// { /// // Logic here ... /// /// scope.Complete(); // last line of using statement /// } /// </code> /// Note that if an exception is thrown scope.Complete will not be called, and the transaction upon leaving the using statement /// will be rolled back. You indicate whether you want the provider to use the esTransactionScope or the System.Transactions.TransactionScope /// class in your .config file. Notice in the config file setting below that providerClass="DataProvider". This indicates that you want to use /// the esTransactionScope class, use providerClass="DataProviderEnterprise" to use System.Transactions.TransactionScope. /// <code> /// &lt;add name="SQL" /// providerMetadataKey="esDefault" /// sqlAccessType="DynamicSQL" /// provider="EntitySpaces.SqlClientProvider" /// providerClass="DataProvider" /// connectionString="User ID=sa;Password=griffinski;Initial Catalog=Northwind;Data Source=localhost" /// databaseVersion="2005"/&gt; /// </code> /// /// /// </remarks>
This is the EntitySpaces ADO.NET connection based transaction class that mimics the System.Transactions.TransactionScope class.
[ "This", "is", "the", "EntitySpaces", "ADO", ".", "NET", "connection", "based", "transaction", "class", "that", "mimics", "the", "System", ".", "Transactions", ".", "TransactionScope", "class", "." ]
public class esTransactionScope : IDisposable { public esTransactionScope() { this.option = esTransactionScopeOption.Required; this.level = esTransactionScope.IsolationLevel; CommonInit(this); this.root.count++; } public esTransactionScope(esTransactionScopeOption option) { if (option == esTransactionScopeOption.None) throw new ArgumentException("'None' cannot be passed"); this.option = option; this.level = esTransactionScope.IsolationLevel; CommonInit(this); this.root.count++; } public esTransactionScope(esTransactionScopeOption option, IsolationLevel level) { this.option = option; this.level = level; CommonInit(this); this.root.count++; } public void Complete() { this.root.count--; if (this.root == this && this.root.count == 0 && this.option != esTransactionScopeOption.Suppress) { foreach (Transaction tx in this.root.transactions.Values) { IDbConnection cn = tx.sqlTx.Connection; tx.sqlTx.Commit(); tx.sqlTx.Dispose(); tx.sqlTx = null; if (cn != null && cn.State == ConnectionState.Open) { cn.Close(); } tx.sqlCn = null; } this.root.transactions.Clear(); if (this.commitList != null) { foreach (ICommittable commit in this.commitList) { commit.Commit(); } commitList.Clear(); } } } #region IDisposable Members void IDisposable.Dispose() { try { if (this.root == this && this.count > 0) { if (this.root.transactions.Count > 0) { Rollback(); return; } } } finally { if (this.commitList != null) { commitList.Clear(); this.commitList = null; } Stack<esTransactionScope> stack = (Stack<esTransactionScope>)Thread.GetData(txSlot); stack.Pop(); } } #endregion private void Rollback() { if (false == this.root.hasRolledBack && this.root.count > 0) { this.root.hasRolledBack = true; foreach (Transaction tx in this.root.transactions.Values) { IDbConnection cn = tx.sqlTx.Connection; try { cn = tx.sqlTx.Connection; tx.sqlTx.Rollback(); tx.sqlTx.Dispose(); } catch { } tx.sqlTx = null; tx.sqlCn = null; if (cn != null && cn.State == ConnectionState.Open) { cn.Close(); } } this.root.transactions.Clear(); this.root.count = 0; } } private class Transaction { public IDbTransaction sqlTx = null; public IDbConnection sqlCn = null; } private Dictionary<string, Transaction> transactions; private List<ICommittable> commitList; private bool hasRolledBack; private int count; private esTransactionScope root; private esTransactionScopeOption option; private IsolationLevel level; #region "static" public delegate IDbConnection CreateIDbConnectionDelegate(); static public esTransactionScopeOption GetCurrentTransactionScopeOption() { esTransactionScope currentTx = GetCurrentTx(); if (currentTx == null) return esTransactionScopeOption.None; else return currentTx.option; } static public void Enlist(IDbCommand cmd, string connectionString, CreateIDbConnectionDelegate creator) { esTransactionScope currentTx = GetCurrentTx(); if (currentTx == null || currentTx.option == esTransactionScopeOption.Suppress) { cmd.Connection = creator(); cmd.Connection.ConnectionString = connectionString; cmd.Connection.Open(); } else { Transaction tx = null; if (currentTx.root.transactions.ContainsKey(connectionString)) { tx = currentTx.root.transactions[connectionString] as Transaction; } else { tx = new Transaction(); IDbConnection cn = creator(); cn.ConnectionString = connectionString; cn.Open(); tx.sqlCn = cn; if (_isolationLevel != IsolationLevel.Unspecified) { tx.sqlTx = cn.BeginTransaction(_isolationLevel); } else { tx.sqlTx = cn.BeginTransaction(); } currentTx.root.transactions[connectionString] = tx; } cmd.Connection = tx.sqlTx.Connection; cmd.Transaction = tx.sqlTx; } } static public void DeEnlist(IDbCommand cmd) { esTransactionScope current = GetCurrentTx(); if (current == null || current.option == esTransactionScopeOption.Suppress) { cmd.Connection.Close(); } } static public bool AddForCommit(ICommittable commit) { esTransactionScope current = GetCurrentTx(); if (current != null) { if (current.commitList == null) { current.commitList = new List<ICommittable>(); } current.commitList.Add(commit); return true; } else { return false; } } static protected void CommonInit(esTransactionScope tx) { Stack<esTransactionScope> stack; object obj = Thread.GetData(txSlot); if (obj == null) { stack = new Stack<esTransactionScope>(); Thread.SetData(txSlot, stack); } else { stack = (Stack<esTransactionScope>)obj; } if (tx.option == esTransactionScopeOption.Required) { foreach (esTransactionScope esTrans in stack) { if (esTrans.option != esTransactionScopeOption.Suppress && esTrans == esTrans.root) { tx.root = esTrans; break; } } } if (tx.root == null) { tx.root = tx; tx.transactions = new Dictionary<string, Transaction>(); } stack.Push(tx); } static private esTransactionScope GetCurrentTx() { esTransactionScope tx = null; object o = Thread.GetData(txSlot); if(o != null) { Stack<esTransactionScope> stack = o as Stack<esTransactionScope>; if (stack.Count > 0) { tx = stack.Peek(); } } return tx; } public static IsolationLevel IsolationLevel { get { return _isolationLevel; } set { _isolationLevel = value; } } private static IsolationLevel _isolationLevel = IsolationLevel.Unspecified; private static LocalDataStoreSlot txSlot = Thread.AllocateDataSlot(); #endregion }
[ "public", "class", "esTransactionScope", ":", "IDisposable", "{", "public", "esTransactionScope", "(", ")", "{", "this", ".", "option", "=", "esTransactionScopeOption", ".", "Required", ";", "this", ".", "level", "=", "esTransactionScope", ".", "IsolationLevel", ";", "CommonInit", "(", "this", ")", ";", "this", ".", "root", ".", "count", "++", ";", "}", "public", "esTransactionScope", "(", "esTransactionScopeOption", "option", ")", "{", "if", "(", "option", "==", "esTransactionScopeOption", ".", "None", ")", "throw", "new", "ArgumentException", "(", "\"", "'None' cannot be passed", "\"", ")", ";", "this", ".", "option", "=", "option", ";", "this", ".", "level", "=", "esTransactionScope", ".", "IsolationLevel", ";", "CommonInit", "(", "this", ")", ";", "this", ".", "root", ".", "count", "++", ";", "}", "public", "esTransactionScope", "(", "esTransactionScopeOption", "option", ",", "IsolationLevel", "level", ")", "{", "this", ".", "option", "=", "option", ";", "this", ".", "level", "=", "level", ";", "CommonInit", "(", "this", ")", ";", "this", ".", "root", ".", "count", "++", ";", "}", "public", "void", "Complete", "(", ")", "{", "this", ".", "root", ".", "count", "--", ";", "if", "(", "this", ".", "root", "==", "this", "&&", "this", ".", "root", ".", "count", "==", "0", "&&", "this", ".", "option", "!=", "esTransactionScopeOption", ".", "Suppress", ")", "{", "foreach", "(", "Transaction", "tx", "in", "this", ".", "root", ".", "transactions", ".", "Values", ")", "{", "IDbConnection", "cn", "=", "tx", ".", "sqlTx", ".", "Connection", ";", "tx", ".", "sqlTx", ".", "Commit", "(", ")", ";", "tx", ".", "sqlTx", ".", "Dispose", "(", ")", ";", "tx", ".", "sqlTx", "=", "null", ";", "if", "(", "cn", "!=", "null", "&&", "cn", ".", "State", "==", "ConnectionState", ".", "Open", ")", "{", "cn", ".", "Close", "(", ")", ";", "}", "tx", ".", "sqlCn", "=", "null", ";", "}", "this", ".", "root", ".", "transactions", ".", "Clear", "(", ")", ";", "if", "(", "this", ".", "commitList", "!=", "null", ")", "{", "foreach", "(", "ICommittable", "commit", "in", "this", ".", "commitList", ")", "{", "commit", ".", "Commit", "(", ")", ";", "}", "commitList", ".", "Clear", "(", ")", ";", "}", "}", "}", "region", " IDisposable Members", "void", "IDisposable", ".", "Dispose", "(", ")", "{", "try", "{", "if", "(", "this", ".", "root", "==", "this", "&&", "this", ".", "count", ">", "0", ")", "{", "if", "(", "this", ".", "root", ".", "transactions", ".", "Count", ">", "0", ")", "{", "Rollback", "(", ")", ";", "return", ";", "}", "}", "}", "finally", "{", "if", "(", "this", ".", "commitList", "!=", "null", ")", "{", "commitList", ".", "Clear", "(", ")", ";", "this", ".", "commitList", "=", "null", ";", "}", "Stack", "<", "esTransactionScope", ">", "stack", "=", "(", "Stack", "<", "esTransactionScope", ">", ")", "Thread", ".", "GetData", "(", "txSlot", ")", ";", "stack", ".", "Pop", "(", ")", ";", "}", "}", "endregion", "private", "void", "Rollback", "(", ")", "{", "if", "(", "false", "==", "this", ".", "root", ".", "hasRolledBack", "&&", "this", ".", "root", ".", "count", ">", "0", ")", "{", "this", ".", "root", ".", "hasRolledBack", "=", "true", ";", "foreach", "(", "Transaction", "tx", "in", "this", ".", "root", ".", "transactions", ".", "Values", ")", "{", "IDbConnection", "cn", "=", "tx", ".", "sqlTx", ".", "Connection", ";", "try", "{", "cn", "=", "tx", ".", "sqlTx", ".", "Connection", ";", "tx", ".", "sqlTx", ".", "Rollback", "(", ")", ";", "tx", ".", "sqlTx", ".", "Dispose", "(", ")", ";", "}", "catch", "{", "}", "tx", ".", "sqlTx", "=", "null", ";", "tx", ".", "sqlCn", "=", "null", ";", "if", "(", "cn", "!=", "null", "&&", "cn", ".", "State", "==", "ConnectionState", ".", "Open", ")", "{", "cn", ".", "Close", "(", ")", ";", "}", "}", "this", ".", "root", ".", "transactions", ".", "Clear", "(", ")", ";", "this", ".", "root", ".", "count", "=", "0", ";", "}", "}", "private", "class", "Transaction", "{", "public", "IDbTransaction", "sqlTx", "=", "null", ";", "public", "IDbConnection", "sqlCn", "=", "null", ";", "}", "private", "Dictionary", "<", "string", ",", "Transaction", ">", "transactions", ";", "private", "List", "<", "ICommittable", ">", "commitList", ";", "private", "bool", "hasRolledBack", ";", "private", "int", "count", ";", "private", "esTransactionScope", "root", ";", "private", "esTransactionScopeOption", "option", ";", "private", "IsolationLevel", "level", ";", "region", " \"static\"", "public", "delegate", "IDbConnection", "CreateIDbConnectionDelegate", "(", ")", ";", "static", "public", "esTransactionScopeOption", "GetCurrentTransactionScopeOption", "(", ")", "{", "esTransactionScope", "currentTx", "=", "GetCurrentTx", "(", ")", ";", "if", "(", "currentTx", "==", "null", ")", "return", "esTransactionScopeOption", ".", "None", ";", "else", "return", "currentTx", ".", "option", ";", "}", "static", "public", "void", "Enlist", "(", "IDbCommand", "cmd", ",", "string", "connectionString", ",", "CreateIDbConnectionDelegate", "creator", ")", "{", "esTransactionScope", "currentTx", "=", "GetCurrentTx", "(", ")", ";", "if", "(", "currentTx", "==", "null", "||", "currentTx", ".", "option", "==", "esTransactionScopeOption", ".", "Suppress", ")", "{", "cmd", ".", "Connection", "=", "creator", "(", ")", ";", "cmd", ".", "Connection", ".", "ConnectionString", "=", "connectionString", ";", "cmd", ".", "Connection", ".", "Open", "(", ")", ";", "}", "else", "{", "Transaction", "tx", "=", "null", ";", "if", "(", "currentTx", ".", "root", ".", "transactions", ".", "ContainsKey", "(", "connectionString", ")", ")", "{", "tx", "=", "currentTx", ".", "root", ".", "transactions", "[", "connectionString", "]", "as", "Transaction", ";", "}", "else", "{", "tx", "=", "new", "Transaction", "(", ")", ";", "IDbConnection", "cn", "=", "creator", "(", ")", ";", "cn", ".", "ConnectionString", "=", "connectionString", ";", "cn", ".", "Open", "(", ")", ";", "tx", ".", "sqlCn", "=", "cn", ";", "if", "(", "_isolationLevel", "!=", "IsolationLevel", ".", "Unspecified", ")", "{", "tx", ".", "sqlTx", "=", "cn", ".", "BeginTransaction", "(", "_isolationLevel", ")", ";", "}", "else", "{", "tx", ".", "sqlTx", "=", "cn", ".", "BeginTransaction", "(", ")", ";", "}", "currentTx", ".", "root", ".", "transactions", "[", "connectionString", "]", "=", "tx", ";", "}", "cmd", ".", "Connection", "=", "tx", ".", "sqlTx", ".", "Connection", ";", "cmd", ".", "Transaction", "=", "tx", ".", "sqlTx", ";", "}", "}", "static", "public", "void", "DeEnlist", "(", "IDbCommand", "cmd", ")", "{", "esTransactionScope", "current", "=", "GetCurrentTx", "(", ")", ";", "if", "(", "current", "==", "null", "||", "current", ".", "option", "==", "esTransactionScopeOption", ".", "Suppress", ")", "{", "cmd", ".", "Connection", ".", "Close", "(", ")", ";", "}", "}", "static", "public", "bool", "AddForCommit", "(", "ICommittable", "commit", ")", "{", "esTransactionScope", "current", "=", "GetCurrentTx", "(", ")", ";", "if", "(", "current", "!=", "null", ")", "{", "if", "(", "current", ".", "commitList", "==", "null", ")", "{", "current", ".", "commitList", "=", "new", "List", "<", "ICommittable", ">", "(", ")", ";", "}", "current", ".", "commitList", ".", "Add", "(", "commit", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "static", "protected", "void", "CommonInit", "(", "esTransactionScope", "tx", ")", "{", "Stack", "<", "esTransactionScope", ">", "stack", ";", "object", "obj", "=", "Thread", ".", "GetData", "(", "txSlot", ")", ";", "if", "(", "obj", "==", "null", ")", "{", "stack", "=", "new", "Stack", "<", "esTransactionScope", ">", "(", ")", ";", "Thread", ".", "SetData", "(", "txSlot", ",", "stack", ")", ";", "}", "else", "{", "stack", "=", "(", "Stack", "<", "esTransactionScope", ">", ")", "obj", ";", "}", "if", "(", "tx", ".", "option", "==", "esTransactionScopeOption", ".", "Required", ")", "{", "foreach", "(", "esTransactionScope", "esTrans", "in", "stack", ")", "{", "if", "(", "esTrans", ".", "option", "!=", "esTransactionScopeOption", ".", "Suppress", "&&", "esTrans", "==", "esTrans", ".", "root", ")", "{", "tx", ".", "root", "=", "esTrans", ";", "break", ";", "}", "}", "}", "if", "(", "tx", ".", "root", "==", "null", ")", "{", "tx", ".", "root", "=", "tx", ";", "tx", ".", "transactions", "=", "new", "Dictionary", "<", "string", ",", "Transaction", ">", "(", ")", ";", "}", "stack", ".", "Push", "(", "tx", ")", ";", "}", "static", "private", "esTransactionScope", "GetCurrentTx", "(", ")", "{", "esTransactionScope", "tx", "=", "null", ";", "object", "o", "=", "Thread", ".", "GetData", "(", "txSlot", ")", ";", "if", "(", "o", "!=", "null", ")", "{", "Stack", "<", "esTransactionScope", ">", "stack", "=", "o", "as", "Stack", "<", "esTransactionScope", ">", ";", "if", "(", "stack", ".", "Count", ">", "0", ")", "{", "tx", "=", "stack", ".", "Peek", "(", ")", ";", "}", "}", "return", "tx", ";", "}", "public", "static", "IsolationLevel", "IsolationLevel", "{", "get", "{", "return", "_isolationLevel", ";", "}", "set", "{", "_isolationLevel", "=", "value", ";", "}", "}", "private", "static", "IsolationLevel", "_isolationLevel", "=", "IsolationLevel", ".", "Unspecified", ";", "private", "static", "LocalDataStoreSlot", "txSlot", "=", "Thread", ".", "AllocateDataSlot", "(", ")", ";", "endregion", "}" ]
This is the EntitySpaces ADO.NET connection based transaction class that mimics the System.Transactions.TransactionScope class.
[ "This", "is", "the", "EntitySpaces", "ADO", ".", "NET", "connection", "based", "transaction", "class", "that", "mimics", "the", "System", ".", "Transactions", ".", "TransactionScope", "class", "." ]
[ "/// <summary>", "/// The default constructor, this transactions <see cref=\"esTransactionScopeOption\"/> will be", "/// set to Required. The IsolationLevel is set to Unspecified.", "/// <code>", "/// using (esTransactionScope scope = new esTransactionScope())", "/// {", "///\t\t// Do your work here", "///\t\tscope.Complete();", "/// }", "/// </code>", "/// </summary>", "/// <summary>", "/// Use this constructor to control the esTransactionScopeOption as it applies", "/// to this transaction.", "/// <code>", "/// using (esTransactionScope scope = new esTransactionScope(esTransactionScopeOption.RequiresNew))", "/// {", "///\t\t// Do your work here", "///\t\tscope.Complete();", "/// }", "/// </code>", "/// </summary>", "/// <param name=\"option\">See <see cref=\"esTransactionScopeOption\"/></param>", "/// <summary>", "/// Use this constructor to control the esTransactionScopeOption as it applies", "/// to this transaction.", "/// <code>", "/// using (esTransactionScope scope = new ", "/// esTransactionScope(esTransactionScopeOption.RequiresNew, IsolationLevel.ReadCommitted))", "/// {", "///\t\t// Do your work here", "///\t\tscope.Complete();", "/// }", "/// </code>", "/// </summary>", "/// <param name=\"option\">See <see cref=\"esTransactionScopeOption\"/></param>", "/// <param name=\"level\">See IsolationLevel in the System.Data namespace</param>", "/// <summary>", "/// You must call Complete to commit the transaction. Calls and transactions can be nested, only the final outer call to", "/// Complete will commit the transaction.", "/// </summary>", "/// <summary>", "/// Internal. Called when the \"using\" statement is exited.", "/// </summary>", "// Somebody didn't call Complete, we must roll back ...", "/// <summary>", "/// Internal method, called if the \"using\" statement is left without calling scope.Complete()", "/// </summary>", "// It may look as though we are eating an exception here", "// but this method is private and only called when we ", "// have already received an error, we don't want our cleanup", "// code to cloud the issue.", "// We might have multple transactions going at the same time.", "// There's one per connnection string", "/// <summary>", "/// EntitySpaces providers register this callback so that the esTransactionScope class can ask it to create the proper", "/// type of connection, ie, SqlConnection, OracleConnection, OleDbConnection and so on ...", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// This can be used to get the esTransactionScopeOption from the current esTransactionScope (remember transactions can be nested).", "/// If there is no on-going transaction then esTransactionScopeOption.None is returned.", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// You should never call this directly, the providers call this method.", "/// </summary>", "/// <param name=\"cmd\">The command to enlist into a transaction</param>", "/// <param name=\"connectionString\">The connection string passed to the CreateIDbConnectionDelegate delegate</param>", "/// <param name=\"creator\">The delegate previously registered by the provider</param>", "// The .NET framework has a bug in that the IDbTransaction only maintains", "// a weak reference to the Connection, thus, we put a strong reference ", "// on it.", "/// <summary>", "/// You should never call this directly, the providers call this method.", "/// </summary>", "/// <param name=\"cmd\">The command to enlist into a transaction</param>", "/// <summary>", "/// You should never call this directly, EntitySpaces calls this internally.", "/// </summary>", "/// <param name=\"commit\">Any class that implements ICommittable</param>", "/// <returns>True if successful</returns>", "/// <summary>", "/// This is the common constructor logic, tx is \"this\" from the constructor", "/// </summary>", "/// <param name=\"tx\"></param>", "// See if our stack is already created (there is only one per thread)", "// If this transaction is required we need to set it's root", "// The root can be either a Requires or RequiresNew, and a root always points to", "// itself, therefore, as long as it's not a Suppress and it's pointing to itself", "// then we know this the next root up on the stack", "// If we didn't find a root, then we are by definition the root", "/// <summary>", "/// Internal method.", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// This is the Transaction's strength. The default is \"IsolationLevel.Unspecified, the strongest is \"IsolationLevel.Serializable\" which is what", "/// is recommended for serious enterprize level projects.", "/// </summary>" ]
[ { "param": "IDisposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDisposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "EntitySpaces supports two transactions models, connection based via this class (esTransactionScope) and the\nnew System.Transactions.TransactionScope. Some databases such as Microsoft Access don't support the new System.Transactions.TransactionScope\nclass. And still there are other cases where the System.Transactions.TransactionScope class cannot be used as is the case with a lot\nof hosting companies. Thus EntitySpaces provides a very nice ADO.NET connection based transaction handler.\n\nThe Syntax should be as follows.\n\nusing (esTransactionScope scope = new esTransactionScope())\n{\nLogic here\n\nscope.Complete(); // last line of using statement\n}\n\n", "docstring_tokens": [ "EntitySpaces", "supports", "two", "transactions", "models", "connection", "based", "via", "this", "class", "(", "esTransactionScope", ")", "and", "the", "new", "System", ".", "Transactions", ".", "TransactionScope", ".", "Some", "databases", "such", "as", "Microsoft", "Access", "don", "'", "t", "support", "the", "new", "System", ".", "Transactions", ".", "TransactionScope", "class", ".", "And", "still", "there", "are", "other", "cases", "where", "the", "System", ".", "Transactions", ".", "TransactionScope", "class", "cannot", "be", "used", "as", "is", "the", "case", "with", "a", "lot", "of", "hosting", "companies", ".", "Thus", "EntitySpaces", "provides", "a", "very", "nice", "ADO", ".", "NET", "connection", "based", "transaction", "handler", ".", "The", "Syntax", "should", "be", "as", "follows", ".", "using", "(", "esTransactionScope", "scope", "=", "new", "esTransactionScope", "()", ")", "{", "Logic", "here", "scope", ".", "Complete", "()", ";", "//", "last", "line", "of", "using", "statement", "}" ] } ] }
false
16
1,449
390
c049a72b8252369fc809a3dacbfa0843d8db1de0
mjsottile/javagep
jgep/JavaGEP/src/jGEP/ArithmeticIndividual.java
[ "BSD-2-Clause" ]
Java
ArithmeticExpressionNode
/** * Inner class implementing the specific expression node this * individual will use. * * Inner classes are good for this since the node type is intimately * bound to the individual, and we don't want it available outside. * When we pass it out (if ever), others can use it if they * expect a generic ExpressionNode object. * * @author Matthew Sottile * @version 1.0 */
Inner class implementing the specific expression node this individual will use. Inner classes are good for this since the node type is intimately bound to the individual, and we don't want it available outside. When we pass it out (if ever), others can use it if they expect a generic ExpressionNode object. @author Matthew Sottile @version 1.0
[ "Inner", "class", "implementing", "the", "specific", "expression", "node", "this", "individual", "will", "use", ".", "Inner", "classes", "are", "good", "for", "this", "since", "the", "node", "type", "is", "intimately", "bound", "to", "the", "individual", "and", "we", "don", "'", "t", "want", "it", "available", "outside", ".", "When", "we", "pass", "it", "out", "(", "if", "ever", ")", "others", "can", "use", "it", "if", "they", "expect", "a", "generic", "ExpressionNode", "object", ".", "@author", "Matthew", "Sottile", "@version", "1", ".", "0" ]
class ArithmeticExpressionNode implements ExpressionNode { private ArithmeticExpressionNode left, right; private char c; public ArithmeticExpressionNode(char c) { this.c = c; } public String stringRepresentation() { String s = ""; if (genome.isFunction(c)) { s = "("+left.stringRepresentation() + " " + c + " " + right.stringRepresentation() + ")"; } else { s = ""+c; } return s; } public Object evaluate(java.util.Hashtable values) throws Exception { Double lval = null; Double rval = null; if (genome.isFunction(c)) { switch(c) { case '+': lval = (Double)left.evaluate(values); rval = (Double)right.evaluate(values); return new Double(lval.doubleValue() + rval.doubleValue()); case '-': lval = (Double)left.evaluate(values); rval = (Double)right.evaluate(values); return new Double(lval.doubleValue() - rval.doubleValue()); case '/': rval = (Double)right.evaluate(values); if (rval.doubleValue() == 0.0) { throw new Exception("Division by zero in evaluate."); } lval = (Double)left.evaluate(values); return new Double(lval.doubleValue() / rval.doubleValue()); case '*': lval = (Double)left.evaluate(values); rval = (Double)right.evaluate(values); return new Double(lval.doubleValue() * rval.doubleValue()); default: throw new Exception("Unimplemented function : "+c); } } else { Double value = (Double)values.get(""+c); if (value == null) { throw new Exception("No value named "+c); } return value; } } protected void setLeft(ArithmeticExpressionNode l) { left = l; } protected void setRight(ArithmeticExpressionNode r) { right = r; } }
[ "class", "ArithmeticExpressionNode", "implements", "ExpressionNode", "{", "private", "ArithmeticExpressionNode", "left", ",", "right", ";", "private", "char", "c", ";", "public", "ArithmeticExpressionNode", "(", "char", "c", ")", "{", "this", ".", "c", "=", "c", ";", "}", "public", "String", "stringRepresentation", "(", ")", "{", "String", "s", "=", "\"", "\"", ";", "if", "(", "genome", ".", "isFunction", "(", "c", ")", ")", "{", "s", "=", "\"", "(", "\"", "+", "left", ".", "stringRepresentation", "(", ")", "+", "\"", " ", "\"", "+", "c", "+", "\"", " ", "\"", "+", "right", ".", "stringRepresentation", "(", ")", "+", "\"", ")", "\"", ";", "}", "else", "{", "s", "=", "\"", "\"", "+", "c", ";", "}", "return", "s", ";", "}", "public", "Object", "evaluate", "(", "java", ".", "util", ".", "Hashtable", "values", ")", "throws", "Exception", "{", "Double", "lval", "=", "null", ";", "Double", "rval", "=", "null", ";", "if", "(", "genome", ".", "isFunction", "(", "c", ")", ")", "{", "switch", "(", "c", ")", "{", "case", "'+'", ":", "lval", "=", "(", "Double", ")", "left", ".", "evaluate", "(", "values", ")", ";", "rval", "=", "(", "Double", ")", "right", ".", "evaluate", "(", "values", ")", ";", "return", "new", "Double", "(", "lval", ".", "doubleValue", "(", ")", "+", "rval", ".", "doubleValue", "(", ")", ")", ";", "case", "'-'", ":", "lval", "=", "(", "Double", ")", "left", ".", "evaluate", "(", "values", ")", ";", "rval", "=", "(", "Double", ")", "right", ".", "evaluate", "(", "values", ")", ";", "return", "new", "Double", "(", "lval", ".", "doubleValue", "(", ")", "-", "rval", ".", "doubleValue", "(", ")", ")", ";", "case", "'/'", ":", "rval", "=", "(", "Double", ")", "right", ".", "evaluate", "(", "values", ")", ";", "if", "(", "rval", ".", "doubleValue", "(", ")", "==", "0.0", ")", "{", "throw", "new", "Exception", "(", "\"", "Division by zero in evaluate.", "\"", ")", ";", "}", "lval", "=", "(", "Double", ")", "left", ".", "evaluate", "(", "values", ")", ";", "return", "new", "Double", "(", "lval", ".", "doubleValue", "(", ")", "/", "rval", ".", "doubleValue", "(", ")", ")", ";", "case", "'*'", ":", "lval", "=", "(", "Double", ")", "left", ".", "evaluate", "(", "values", ")", ";", "rval", "=", "(", "Double", ")", "right", ".", "evaluate", "(", "values", ")", ";", "return", "new", "Double", "(", "lval", ".", "doubleValue", "(", ")", "*", "rval", ".", "doubleValue", "(", ")", ")", ";", "default", ":", "throw", "new", "Exception", "(", "\"", "Unimplemented function : ", "\"", "+", "c", ")", ";", "}", "}", "else", "{", "Double", "value", "=", "(", "Double", ")", "values", ".", "get", "(", "\"", "\"", "+", "c", ")", ";", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"", "No value named ", "\"", "+", "c", ")", ";", "}", "return", "value", ";", "}", "}", "protected", "void", "setLeft", "(", "ArithmeticExpressionNode", "l", ")", "{", "left", "=", "l", ";", "}", "protected", "void", "setRight", "(", "ArithmeticExpressionNode", "r", ")", "{", "right", "=", "r", ";", "}", "}" ]
Inner class implementing the specific expression node this individual will use.
[ "Inner", "class", "implementing", "the", "specific", "expression", "node", "this", "individual", "will", "use", "." ]
[]
[ { "param": "ExpressionNode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ExpressionNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
443
102
b907e18b4f6362a3396779efe5ec5e31f6aa3dd9
SpaceCadetEve/CameraControlLib
CameraControlLib/Camera.cs
[ "MIT" ]
C#
Camera
/// <summary> /// Provides access to the properties of a camera. /// </summary> /// <remarks> /// To create a Camera, use Camera.GetAll() to enumerate the /// available video capture devices. This method returns a list of /// camera descriptors and calling the Create() method on the camera /// descriptor will instantiate the Camera device. /// /// The descriptors don't store any unmanaged resources and so don't need /// resource cleanup, but the Camera object should be disposed when /// finished with it. /// </remarks>
Provides access to the properties of a camera.
[ "Provides", "access", "to", "the", "properties", "of", "a", "camera", "." ]
public class Camera : IDisposable { private DsDevice _device; private IBaseFilter _filter; private Dictionary<string, CameraProperty> _cameraProperties = new Dictionary<string, CameraProperty>(); public CameraProperty Focus { get { return Get("Focus"); } } public CameraProperty Exposure { get { return Get("Exposure"); } } public CameraProperty Zoom { get { return Get("Zoom"); } } public CameraProperty Pan { get { return Get("Pan"); } } public CameraProperty Tilt { get { return Get("Tilt"); } } public CameraProperty Roll { get { return Get("Roll"); } } public CameraProperty Iris { get { return Get("Iris"); } } public CameraProperty Brightness { get { return Get("Brightness"); } } public CameraProperty Contrast { get { return Get("Contrast"); } } public CameraProperty Hue { get { return Get("Hue"); } } public CameraProperty Saturation { get { return Get("Saturation"); } } public CameraProperty Sharpness { get { return Get("Sharpness"); } } public CameraProperty Gamma { get { return Get("Gamma"); } } public CameraProperty ColorEnable { get { return Get("ColorEnable"); } } public CameraProperty WhiteBalance { get { return Get("WhiteBalance"); } } public CameraProperty BacklightCompensation { get { return Get("BacklightCompensation"); } } public CameraProperty Gain { get { return Get("Gain"); } } internal IBaseFilter Filter { get { return _filter; } } internal Camera(DsDevice device) { _device = device; IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; IMoniker i = _device.Mon as IMoniker; graphBuilder.AddSourceFilterForMoniker(i, null, _device.Name, out _filter); RegisterProperties(); } private readonly static List<CameraPropertyDescriptor> s_knownProperties = new List<CameraPropertyDescriptor>() { CamControlProperty.CreateDescriptor("Focus", "Focus", CameraControlProperty.Focus), CamControlProperty.CreateDescriptor("Exposure", "Exposure time", CameraControlProperty.Exposure), CamControlProperty.CreateDescriptor("Zoom", "Zoom", CameraControlProperty.Zoom), CamControlProperty.CreateDescriptor("Pan", "Pan", CameraControlProperty.Pan), CamControlProperty.CreateDescriptor("Tilt", "Tilt", CameraControlProperty.Tilt), CamControlProperty.CreateDescriptor("Roll", "Roll", CameraControlProperty.Roll), CamControlProperty.CreateDescriptor("Iris", "Iris", CameraControlProperty.Iris), VideoProcAmpCameraProperty.CreateDescriptor("Brightness", "Brightness", VideoProcAmpProperty.Brightness), VideoProcAmpCameraProperty.CreateDescriptor("Contrast", "Contrast", VideoProcAmpProperty.Contrast), VideoProcAmpCameraProperty.CreateDescriptor("Hue", "Hue", VideoProcAmpProperty.Hue), VideoProcAmpCameraProperty.CreateDescriptor("Saturation", "Saturation", VideoProcAmpProperty.Saturation), VideoProcAmpCameraProperty.CreateDescriptor("Sharpness", "Sharpness", VideoProcAmpProperty.Sharpness), VideoProcAmpCameraProperty.CreateDescriptor("Gamma", "Gamma", VideoProcAmpProperty.Gamma), VideoProcAmpCameraProperty.CreateDescriptor("ColorEnable", "Color Enable", VideoProcAmpProperty.ColorEnable), VideoProcAmpCameraProperty.CreateDescriptor("WhiteBalance", "White Balance", VideoProcAmpProperty.WhiteBalance), VideoProcAmpCameraProperty.CreateDescriptor("BacklightCompensation", "Backlight Compensation", VideoProcAmpProperty.BacklightCompensation), VideoProcAmpCameraProperty.CreateDescriptor("Gain", "Gain", VideoProcAmpProperty.Gain) }; public CameraProperty Get(string propertyId) { return _cameraProperties[propertyId]; } public static System.Collections.Generic.IReadOnlyList<CameraPropertyDescriptor> KnownProperties { get { return s_knownProperties.AsReadOnly(); } } private void RegisterProperties() { foreach (var descriptor in Camera.KnownProperties) { _cameraProperties[descriptor.Id] = descriptor.Create(this); } } public List<CameraProperty> GetProperties() { return _cameraProperties.Values.ToList(); } public List<CameraProperty> GetSupportedProperties() { return _cameraProperties.Values.Where(p => p.Supported).ToList(); } public void Refresh() { foreach (var prop in _cameraProperties.Values) prop.Refresh(); } public void Save() { foreach (var prop in _cameraProperties.Values) prop.Save(); } public void ResetToDefault() { foreach (var prop in _cameraProperties.Values) prop.ResetToDefault(); } public static IList<CameraDescriptor> GetAll() { return CameraDescriptor.GetAll(); } #region IDisposable Support private bool _disposedValue = false; protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { } _disposedValue = true; } } ~Camera() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion }
[ "public", "class", "Camera", ":", "IDisposable", "{", "private", "DsDevice", "_device", ";", "private", "IBaseFilter", "_filter", ";", "private", "Dictionary", "<", "string", ",", "CameraProperty", ">", "_cameraProperties", "=", "new", "Dictionary", "<", "string", ",", "CameraProperty", ">", "(", ")", ";", "public", "CameraProperty", "Focus", "{", "get", "{", "return", "Get", "(", "\"", "Focus", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Exposure", "{", "get", "{", "return", "Get", "(", "\"", "Exposure", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Zoom", "{", "get", "{", "return", "Get", "(", "\"", "Zoom", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Pan", "{", "get", "{", "return", "Get", "(", "\"", "Pan", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Tilt", "{", "get", "{", "return", "Get", "(", "\"", "Tilt", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Roll", "{", "get", "{", "return", "Get", "(", "\"", "Roll", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Iris", "{", "get", "{", "return", "Get", "(", "\"", "Iris", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Brightness", "{", "get", "{", "return", "Get", "(", "\"", "Brightness", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Contrast", "{", "get", "{", "return", "Get", "(", "\"", "Contrast", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Hue", "{", "get", "{", "return", "Get", "(", "\"", "Hue", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Saturation", "{", "get", "{", "return", "Get", "(", "\"", "Saturation", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Sharpness", "{", "get", "{", "return", "Get", "(", "\"", "Sharpness", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Gamma", "{", "get", "{", "return", "Get", "(", "\"", "Gamma", "\"", ")", ";", "}", "}", "public", "CameraProperty", "ColorEnable", "{", "get", "{", "return", "Get", "(", "\"", "ColorEnable", "\"", ")", ";", "}", "}", "public", "CameraProperty", "WhiteBalance", "{", "get", "{", "return", "Get", "(", "\"", "WhiteBalance", "\"", ")", ";", "}", "}", "public", "CameraProperty", "BacklightCompensation", "{", "get", "{", "return", "Get", "(", "\"", "BacklightCompensation", "\"", ")", ";", "}", "}", "public", "CameraProperty", "Gain", "{", "get", "{", "return", "Get", "(", "\"", "Gain", "\"", ")", ";", "}", "}", "internal", "IBaseFilter", "Filter", "{", "get", "{", "return", "_filter", ";", "}", "}", "internal", "Camera", "(", "DsDevice", "device", ")", "{", "_device", "=", "device", ";", "IFilterGraph2", "graphBuilder", "=", "new", "FilterGraph", "(", ")", "as", "IFilterGraph2", ";", "IMoniker", "i", "=", "_device", ".", "Mon", "as", "IMoniker", ";", "graphBuilder", ".", "AddSourceFilterForMoniker", "(", "i", ",", "null", ",", "_device", ".", "Name", ",", "out", "_filter", ")", ";", "RegisterProperties", "(", ")", ";", "}", "private", "readonly", "static", "List", "<", "CameraPropertyDescriptor", ">", "s_knownProperties", "=", "new", "List", "<", "CameraPropertyDescriptor", ">", "(", ")", "{", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Focus", "\"", ",", "\"", "Focus", "\"", ",", "CameraControlProperty", ".", "Focus", ")", ",", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Exposure", "\"", ",", "\"", "Exposure time", "\"", ",", "CameraControlProperty", ".", "Exposure", ")", ",", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Zoom", "\"", ",", "\"", "Zoom", "\"", ",", "CameraControlProperty", ".", "Zoom", ")", ",", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Pan", "\"", ",", "\"", "Pan", "\"", ",", "CameraControlProperty", ".", "Pan", ")", ",", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Tilt", "\"", ",", "\"", "Tilt", "\"", ",", "CameraControlProperty", ".", "Tilt", ")", ",", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Roll", "\"", ",", "\"", "Roll", "\"", ",", "CameraControlProperty", ".", "Roll", ")", ",", "CamControlProperty", ".", "CreateDescriptor", "(", "\"", "Iris", "\"", ",", "\"", "Iris", "\"", ",", "CameraControlProperty", ".", "Iris", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Brightness", "\"", ",", "\"", "Brightness", "\"", ",", "VideoProcAmpProperty", ".", "Brightness", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Contrast", "\"", ",", "\"", "Contrast", "\"", ",", "VideoProcAmpProperty", ".", "Contrast", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Hue", "\"", ",", "\"", "Hue", "\"", ",", "VideoProcAmpProperty", ".", "Hue", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Saturation", "\"", ",", "\"", "Saturation", "\"", ",", "VideoProcAmpProperty", ".", "Saturation", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Sharpness", "\"", ",", "\"", "Sharpness", "\"", ",", "VideoProcAmpProperty", ".", "Sharpness", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Gamma", "\"", ",", "\"", "Gamma", "\"", ",", "VideoProcAmpProperty", ".", "Gamma", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "ColorEnable", "\"", ",", "\"", "Color Enable", "\"", ",", "VideoProcAmpProperty", ".", "ColorEnable", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "WhiteBalance", "\"", ",", "\"", "White Balance", "\"", ",", "VideoProcAmpProperty", ".", "WhiteBalance", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "BacklightCompensation", "\"", ",", "\"", "Backlight Compensation", "\"", ",", "VideoProcAmpProperty", ".", "BacklightCompensation", ")", ",", "VideoProcAmpCameraProperty", ".", "CreateDescriptor", "(", "\"", "Gain", "\"", ",", "\"", "Gain", "\"", ",", "VideoProcAmpProperty", ".", "Gain", ")", "}", ";", "public", "CameraProperty", "Get", "(", "string", "propertyId", ")", "{", "return", "_cameraProperties", "[", "propertyId", "]", ";", "}", "public", "static", "System", ".", "Collections", ".", "Generic", ".", "IReadOnlyList", "<", "CameraPropertyDescriptor", ">", "KnownProperties", "{", "get", "{", "return", "s_knownProperties", ".", "AsReadOnly", "(", ")", ";", "}", "}", "private", "void", "RegisterProperties", "(", ")", "{", "foreach", "(", "var", "descriptor", "in", "Camera", ".", "KnownProperties", ")", "{", "_cameraProperties", "[", "descriptor", ".", "Id", "]", "=", "descriptor", ".", "Create", "(", "this", ")", ";", "}", "}", "public", "List", "<", "CameraProperty", ">", "GetProperties", "(", ")", "{", "return", "_cameraProperties", ".", "Values", ".", "ToList", "(", ")", ";", "}", "public", "List", "<", "CameraProperty", ">", "GetSupportedProperties", "(", ")", "{", "return", "_cameraProperties", ".", "Values", ".", "Where", "(", "p", "=>", "p", ".", "Supported", ")", ".", "ToList", "(", ")", ";", "}", "public", "void", "Refresh", "(", ")", "{", "foreach", "(", "var", "prop", "in", "_cameraProperties", ".", "Values", ")", "prop", ".", "Refresh", "(", ")", ";", "}", "public", "void", "Save", "(", ")", "{", "foreach", "(", "var", "prop", "in", "_cameraProperties", ".", "Values", ")", "prop", ".", "Save", "(", ")", ";", "}", "public", "void", "ResetToDefault", "(", ")", "{", "foreach", "(", "var", "prop", "in", "_cameraProperties", ".", "Values", ")", "prop", ".", "ResetToDefault", "(", ")", ";", "}", "public", "static", "IList", "<", "CameraDescriptor", ">", "GetAll", "(", ")", "{", "return", "CameraDescriptor", ".", "GetAll", "(", ")", ";", "}", "region", " IDisposable Support", "private", "bool", "_disposedValue", "=", "false", ";", "protected", "virtual", "void", "Dispose", "(", "bool", "disposing", ")", "{", "if", "(", "!", "_disposedValue", ")", "{", "if", "(", "disposing", ")", "{", "}", "_disposedValue", "=", "true", ";", "}", "}", "~", "Camera", "(", ")", "{", "Dispose", "(", "false", ")", ";", "}", "public", "void", "Dispose", "(", ")", "{", "Dispose", "(", "true", ")", ";", "GC", ".", "SuppressFinalize", "(", "this", ")", ";", "}", "endregion", "}" ]
Provides access to the properties of a camera.
[ "Provides", "access", "to", "the", "properties", "of", "a", "camera", "." ]
[ "/// <summary>", "/// Gets a list of all the available properties, even if the camera doesn't appear to support them.", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// Gets a list of the properties supported by this camera.", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// Fetches updated ", "/// </summary>", "// To detect redundant calls", "// TODO: dispose managed state (managed objects).", "// Do not change this code. Put cleanup code in Dispose(bool disposing) above.", "// This code added to correctly implement the disposable pattern.", "// Do not change this code. Put cleanup code in Dispose(bool disposing) above." ]
[ { "param": "IDisposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDisposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "To create a Camera, use Camera.GetAll() to enumerate the\navailable video capture devices. This method returns a list of\ncamera descriptors and calling the Create() method on the camera\ndescriptor will instantiate the Camera device.\n\nThe descriptors don't store any unmanaged resources and so don't need\nresource cleanup, but the Camera object should be disposed when\nfinished with it.", "docstring_tokens": [ "To", "create", "a", "Camera", "use", "Camera", ".", "GetAll", "()", "to", "enumerate", "the", "available", "video", "capture", "devices", ".", "This", "method", "returns", "a", "list", "of", "camera", "descriptors", "and", "calling", "the", "Create", "()", "method", "on", "the", "camera", "descriptor", "will", "instantiate", "the", "Camera", "device", ".", "The", "descriptors", "don", "'", "t", "store", "any", "unmanaged", "resources", "and", "so", "don", "'", "t", "need", "resource", "cleanup", "but", "the", "Camera", "object", "should", "be", "disposed", "when", "finished", "with", "it", "." ] } ] }
false
13
1,144
110
ada385dc1660131debd20174f7988785d09b39db
WeConnect/phonegap-plugins
WindowsPhone/BarcodeScanner/sources/ZXing7_1Port/common/ByteArray.cs
[ "Unlicense" ]
C#
ByteArray
/// <summary> This class implements an array of unsigned bytes. /// /// </summary> /// <author> [email protected] (Daniel Switkin) /// </author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source /// </author>
This class implements an array of unsigned bytes.
[ "This", "class", "implements", "an", "array", "of", "unsigned", "bytes", "." ]
public sealed class ByteArray { public bool Empty { get { return size_Renamed_Field == 0; } } private const int INITIAL_SIZE = 32; private sbyte[] bytes; private int size_Renamed_Field; public ByteArray() { bytes = null; size_Renamed_Field = 0; } public ByteArray(int size) { bytes = new sbyte[size]; this.size_Renamed_Field = size; } public ByteArray(sbyte[] byteArray) { bytes = byteArray; size_Renamed_Field = bytes.Length; } public int at(int index) { return bytes[index] & 0xff; } public void set_Renamed(int index, int value_Renamed) { bytes[index] = (sbyte) value_Renamed; } public int size() { return size_Renamed_Field; } public void appendByte(int value_Renamed) { if (size_Renamed_Field == 0 || size_Renamed_Field >= bytes.Length) { int newSize = System.Math.Max(INITIAL_SIZE, size_Renamed_Field << 1); reserve(newSize); } bytes[size_Renamed_Field] = (sbyte) value_Renamed; size_Renamed_Field++; } public void reserve(int capacity) { if (bytes == null || bytes.Length < capacity) { sbyte[] newArray = new sbyte[capacity]; if (bytes != null) { Array.Copy(bytes, 0, newArray, 0, bytes.Length); } bytes = newArray; } } public void set_Renamed(sbyte[] source, int offset, int count) { bytes = new sbyte[count]; size_Renamed_Field = count; for (int x = 0; x < count; x++) { bytes[x] = source[offset + x]; } } }
[ "public", "sealed", "class", "ByteArray", "{", "public", "bool", "Empty", "{", "get", "{", "return", "size_Renamed_Field", "==", "0", ";", "}", "}", "private", "const", "int", "INITIAL_SIZE", "=", "32", ";", "private", "sbyte", "[", "]", "bytes", ";", "private", "int", "size_Renamed_Field", ";", "public", "ByteArray", "(", ")", "{", "bytes", "=", "null", ";", "size_Renamed_Field", "=", "0", ";", "}", "public", "ByteArray", "(", "int", "size", ")", "{", "bytes", "=", "new", "sbyte", "[", "size", "]", ";", "this", ".", "size_Renamed_Field", "=", "size", ";", "}", "public", "ByteArray", "(", "sbyte", "[", "]", "byteArray", ")", "{", "bytes", "=", "byteArray", ";", "size_Renamed_Field", "=", "bytes", ".", "Length", ";", "}", "public", "int", "at", "(", "int", "index", ")", "{", "return", "bytes", "[", "index", "]", "&", "0xff", ";", "}", "public", "void", "set_Renamed", "(", "int", "index", ",", "int", "value_Renamed", ")", "{", "bytes", "[", "index", "]", "=", "(", "sbyte", ")", "value_Renamed", ";", "}", "public", "int", "size", "(", ")", "{", "return", "size_Renamed_Field", ";", "}", "public", "void", "appendByte", "(", "int", "value_Renamed", ")", "{", "if", "(", "size_Renamed_Field", "==", "0", "||", "size_Renamed_Field", ">=", "bytes", ".", "Length", ")", "{", "int", "newSize", "=", "System", ".", "Math", ".", "Max", "(", "INITIAL_SIZE", ",", "size_Renamed_Field", "<<", "1", ")", ";", "reserve", "(", "newSize", ")", ";", "}", "bytes", "[", "size_Renamed_Field", "]", "=", "(", "sbyte", ")", "value_Renamed", ";", "size_Renamed_Field", "++", ";", "}", "public", "void", "reserve", "(", "int", "capacity", ")", "{", "if", "(", "bytes", "==", "null", "||", "bytes", ".", "Length", "<", "capacity", ")", "{", "sbyte", "[", "]", "newArray", "=", "new", "sbyte", "[", "capacity", "]", ";", "if", "(", "bytes", "!=", "null", ")", "{", "Array", ".", "Copy", "(", "bytes", ",", "0", ",", "newArray", ",", "0", ",", "bytes", ".", "Length", ")", ";", "}", "bytes", "=", "newArray", ";", "}", "}", "public", "void", "set_Renamed", "(", "sbyte", "[", "]", "source", ",", "int", "offset", ",", "int", "count", ")", "{", "bytes", "=", "new", "sbyte", "[", "count", "]", ";", "size_Renamed_Field", "=", "count", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "count", ";", "x", "++", ")", "{", "bytes", "[", "x", "]", "=", "source", "[", "offset", "+", "x", "]", ";", "}", "}", "}" ]
This class implements an array of unsigned bytes.
[ "This", "class", "implements", "an", "array", "of", "unsigned", "bytes", "." ]
[ "/// <summary> Access an unsigned byte at location index.</summary>", "/// <param name=\"index\">The index in the array to access.", "/// </param>", "/// <returns> The unsigned value of the byte as an int.", "/// </returns>", "// Copy count bytes from array source starting at offset." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "author", "docstring": "[email protected] (Daniel Switkin)", "docstring_tokens": [ "dswitkin@google", ".", "com", "(", "Daniel", "Switkin", ")" ] }, { "identifier": "author", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
14
478
77
29986dbf14fb1635ad0f2945a0149a4aff705f9d
myfinance/mfbackend
bundles/api/de.hf.dac.api.security/src/main/java/de/hf/dac/api/security/SecuredResource.java
[ "Apache-2.0" ]
Java
SecuredResource
/** * each secured class (sub class of SecuredResource) can check access right for methods. For this it needs a security-context. * The securityContext derives an OpLevel and a Id from IdentifiableResource and a SecurityProvider from Secured. * The SecurityProvider is responsable to get all rights and rolls for an authenticated user and to check a Table which rights are necessary for the OpLevel and Id * @param <ACCESS_TYPE> enum of allowed access_types e.G. Read and write * @param <RESOURCE_LEVEL> enum of allowed Resource_Levels */
each secured class (sub class of SecuredResource) can check access right for methods. For this it needs a security-context. The securityContext derives an OpLevel and a Id from IdentifiableResource and a SecurityProvider from Secured. The SecurityProvider is responsable to get all rights and rolls for an authenticated user and to check a Table which rights are necessary for the OpLevel and Id @param enum of allowed access_types e.G. Read and write @param enum of allowed Resource_Levels
[ "each", "secured", "class", "(", "sub", "class", "of", "SecuredResource", ")", "can", "check", "access", "right", "for", "methods", ".", "For", "this", "it", "needs", "a", "security", "-", "context", ".", "The", "securityContext", "derives", "an", "OpLevel", "and", "a", "Id", "from", "IdentifiableResource", "and", "a", "SecurityProvider", "from", "Secured", ".", "The", "SecurityProvider", "is", "responsable", "to", "get", "all", "rights", "and", "rolls", "for", "an", "authenticated", "user", "and", "to", "check", "a", "Table", "which", "rights", "are", "necessary", "for", "the", "OpLevel", "and", "Id", "@param", "enum", "of", "allowed", "access_types", "e", ".", "G", ".", "Read", "and", "write", "@param", "enum", "of", "allowed", "Resource_Levels" ]
public abstract class SecuredResource<ACCESS_TYPE extends Enum<ACCESS_TYPE>,RESOURCE_LEVEL extends Enum<RESOURCE_LEVEL>> extends BaseDS { private String resourceId1; private RESOURCE_LEVEL opLevel1; private RootSecurityProvider rootSecurityProvider1; private String resourceId2; private RESOURCE_LEVEL opLevel2; private RootSecurityProvider rootSecurityProvider2; private boolean isInit = false; public SecuredResource() { init(getSecurityContext()); } public <T extends IdentifiableResource<RESOURCE_LEVEL> & Secured> SecuredResource(T resource) { init(resource); } protected abstract <T extends IdentifiableResource<RESOURCE_LEVEL> & Secured> T getSecurityContext(); private <T extends IdentifiableResource<RESOURCE_LEVEL> & Secured> void init(T securityContext){ if(!isInit){ this.resourceId1 = securityContext.getId(); this.opLevel1 = securityContext.getOpLevel(); this.rootSecurityProvider1 = securityContext.getRootSecurityProvider(); this.resourceId2 = securityContext.getId(); this.opLevel2 = securityContext.getOpLevel(); this.rootSecurityProvider2 = securityContext.getRootSecurityProvider(); isInit=true; } } /** * for multiEnvironment operations e.G. if you want to compare two sets of Information from different environments * @param securityContext1 * @param securityContext2 * @param <T1> * @param <T2> */ public <T1 extends IdentifiableResource<RESOURCE_LEVEL> & Secured, T2 extends IdentifiableResource<RESOURCE_LEVEL> & Secured> SecuredResource(T1 securityContext1, T2 securityContext2) { this.resourceId1 = securityContext1.getId(); this.opLevel1 = securityContext1.getOpLevel(); this.rootSecurityProvider1 = securityContext1.getRootSecurityProvider(); this.resourceId2 = securityContext2.getId(); this.opLevel2 = securityContext2.getOpLevel(); this.rootSecurityProvider2 = securityContext2.getRootSecurityProvider(); } public void checkOperationAllowed(ACCESS_TYPE accessType) throws AccessNotAllowedException { StackTraceElement stack = Thread.currentThread().getStackTrace()[2]; String operationId = stack.getMethodName(); checkOperationAllowed(accessType,operationId); } public void checkOperationAllowed(ACCESS_TYPE accessType, String operationId) throws AccessNotAllowedException { boolean allowed = rootSecurityProvider1.isOperationAllowed(accessType, opLevel1, resourceId1, Subject.getSubject(AccessController.getContext()), operationId); if(allowed) return; throw new SecurityException("Not allowed"); } public void checkBinaryOperationAllowed(ACCESS_TYPE accessType, String operationId1, String operationId2) throws AccessNotAllowedException { boolean allowed1 = rootSecurityProvider1.isOperationAllowed(accessType, opLevel1, resourceId1, Subject.getSubject(AccessController.getContext()), operationId1); boolean allowed2 = rootSecurityProvider2.isOperationAllowed(accessType, opLevel2, resourceId2, Subject.getSubject(AccessController.getContext()), operationId2); if(allowed1 && allowed2) return; throw new SecurityException("Not allowed"); } public void checkPassthroughAllowed() { boolean allowed = rootSecurityProvider1.isPassthroughAllowed(opLevel1, resourceId1, Subject.getSubject(AccessController.getContext())); boolean allowed2 = rootSecurityProvider2.isPassthroughAllowed(opLevel2, resourceId2, Subject.getSubject(AccessController.getContext())); if(allowed && allowed2) return; throw new SecurityException("Not allowed"); } }
[ "public", "abstract", "class", "SecuredResource", "<", "ACCESS_TYPE", "extends", "Enum", "<", "ACCESS_TYPE", ">", ",", "RESOURCE_LEVEL", "extends", "Enum", "<", "RESOURCE_LEVEL", ">", ">", "extends", "BaseDS", "{", "private", "String", "resourceId1", ";", "private", "RESOURCE_LEVEL", "opLevel1", ";", "private", "RootSecurityProvider", "rootSecurityProvider1", ";", "private", "String", "resourceId2", ";", "private", "RESOURCE_LEVEL", "opLevel2", ";", "private", "RootSecurityProvider", "rootSecurityProvider2", ";", "private", "boolean", "isInit", "=", "false", ";", "public", "SecuredResource", "(", ")", "{", "init", "(", "getSecurityContext", "(", ")", ")", ";", "}", "public", "<", "T", "extends", "IdentifiableResource", "<", "RESOURCE_LEVEL", ">", "&", "Secured", ">", "SecuredResource", "(", "T", "resource", ")", "{", "init", "(", "resource", ")", ";", "}", "protected", "abstract", "<", "T", "extends", "IdentifiableResource", "<", "RESOURCE_LEVEL", ">", "&", "Secured", ">", "T", "getSecurityContext", "(", ")", ";", "private", "<", "T", "extends", "IdentifiableResource", "<", "RESOURCE_LEVEL", ">", "&", "Secured", ">", "void", "init", "(", "T", "securityContext", ")", "{", "if", "(", "!", "isInit", ")", "{", "this", ".", "resourceId1", "=", "securityContext", ".", "getId", "(", ")", ";", "this", ".", "opLevel1", "=", "securityContext", ".", "getOpLevel", "(", ")", ";", "this", ".", "rootSecurityProvider1", "=", "securityContext", ".", "getRootSecurityProvider", "(", ")", ";", "this", ".", "resourceId2", "=", "securityContext", ".", "getId", "(", ")", ";", "this", ".", "opLevel2", "=", "securityContext", ".", "getOpLevel", "(", ")", ";", "this", ".", "rootSecurityProvider2", "=", "securityContext", ".", "getRootSecurityProvider", "(", ")", ";", "isInit", "=", "true", ";", "}", "}", "/**\n * for multiEnvironment operations e.G. if you want to compare two sets of Information from different environments\n * @param securityContext1\n * @param securityContext2\n * @param <T1>\n * @param <T2>\n */", "public", "<", "T1", "extends", "IdentifiableResource", "<", "RESOURCE_LEVEL", ">", "&", "Secured", ",", "T2", "extends", "IdentifiableResource", "<", "RESOURCE_LEVEL", ">", "&", "Secured", ">", "SecuredResource", "(", "T1", "securityContext1", ",", "T2", "securityContext2", ")", "{", "this", ".", "resourceId1", "=", "securityContext1", ".", "getId", "(", ")", ";", "this", ".", "opLevel1", "=", "securityContext1", ".", "getOpLevel", "(", ")", ";", "this", ".", "rootSecurityProvider1", "=", "securityContext1", ".", "getRootSecurityProvider", "(", ")", ";", "this", ".", "resourceId2", "=", "securityContext2", ".", "getId", "(", ")", ";", "this", ".", "opLevel2", "=", "securityContext2", ".", "getOpLevel", "(", ")", ";", "this", ".", "rootSecurityProvider2", "=", "securityContext2", ".", "getRootSecurityProvider", "(", ")", ";", "}", "public", "void", "checkOperationAllowed", "(", "ACCESS_TYPE", "accessType", ")", "throws", "AccessNotAllowedException", "{", "StackTraceElement", "stack", "=", "Thread", ".", "currentThread", "(", ")", ".", "getStackTrace", "(", ")", "[", "2", "]", ";", "String", "operationId", "=", "stack", ".", "getMethodName", "(", ")", ";", "checkOperationAllowed", "(", "accessType", ",", "operationId", ")", ";", "}", "public", "void", "checkOperationAllowed", "(", "ACCESS_TYPE", "accessType", ",", "String", "operationId", ")", "throws", "AccessNotAllowedException", "{", "boolean", "allowed", "=", "rootSecurityProvider1", ".", "isOperationAllowed", "(", "accessType", ",", "opLevel1", ",", "resourceId1", ",", "Subject", ".", "getSubject", "(", "AccessController", ".", "getContext", "(", ")", ")", ",", "operationId", ")", ";", "if", "(", "allowed", ")", "return", ";", "throw", "new", "SecurityException", "(", "\"", "Not allowed", "\"", ")", ";", "}", "public", "void", "checkBinaryOperationAllowed", "(", "ACCESS_TYPE", "accessType", ",", "String", "operationId1", ",", "String", "operationId2", ")", "throws", "AccessNotAllowedException", "{", "boolean", "allowed1", "=", "rootSecurityProvider1", ".", "isOperationAllowed", "(", "accessType", ",", "opLevel1", ",", "resourceId1", ",", "Subject", ".", "getSubject", "(", "AccessController", ".", "getContext", "(", ")", ")", ",", "operationId1", ")", ";", "boolean", "allowed2", "=", "rootSecurityProvider2", ".", "isOperationAllowed", "(", "accessType", ",", "opLevel2", ",", "resourceId2", ",", "Subject", ".", "getSubject", "(", "AccessController", ".", "getContext", "(", ")", ")", ",", "operationId2", ")", ";", "if", "(", "allowed1", "&&", "allowed2", ")", "return", ";", "throw", "new", "SecurityException", "(", "\"", "Not allowed", "\"", ")", ";", "}", "public", "void", "checkPassthroughAllowed", "(", ")", "{", "boolean", "allowed", "=", "rootSecurityProvider1", ".", "isPassthroughAllowed", "(", "opLevel1", ",", "resourceId1", ",", "Subject", ".", "getSubject", "(", "AccessController", ".", "getContext", "(", ")", ")", ")", ";", "boolean", "allowed2", "=", "rootSecurityProvider2", ".", "isPassthroughAllowed", "(", "opLevel2", ",", "resourceId2", ",", "Subject", ".", "getSubject", "(", "AccessController", ".", "getContext", "(", ")", ")", ")", ";", "if", "(", "allowed", "&&", "allowed2", ")", "return", ";", "throw", "new", "SecurityException", "(", "\"", "Not allowed", "\"", ")", ";", "}", "}" ]
each secured class (sub class of SecuredResource) can check access right for methods.
[ "each", "secured", "class", "(", "sub", "class", "of", "SecuredResource", ")", "can", "check", "access", "right", "for", "methods", "." ]
[]
[ { "param": "BaseDS", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseDS", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
771
117
6161f23f8e529c0dc5b7c4eb93e54a598828517d
TheApplePie/Catalyst
Catalyst/Bindings/Vulkan/PhysicalDevice.cs
[ "MIT" ]
C#
PhysicalDevice
/// <summary> /// Opaque handle to a physical device object. /// <para> /// Vulkan separates the concept of physical and logical devices. A physical device usually /// represents a single device in a system (perhaps made up of several individual hardware /// devices working together), of which there are a finite number. A logical device represents an /// application's view of the device. /// </para> /// </summary>
Opaque handle to a physical device object. Vulkan separates the concept of physical and logical devices. A physical device usually represents a single device in a system (perhaps made up of several individual hardware devices working together), of which there are a finite number. A logical device represents an application's view of the device.
[ "Opaque", "handle", "to", "a", "physical", "device", "object", ".", "Vulkan", "separates", "the", "concept", "of", "physical", "and", "logical", "devices", ".", "A", "physical", "device", "usually", "represents", "a", "single", "device", "in", "a", "system", "(", "perhaps", "made", "up", "of", "several", "individual", "hardware", "devices", "working", "together", ")", "of", "which", "there", "are", "a", "finite", "number", ".", "A", "logical", "device", "represents", "an", "application", "'", "s", "view", "of", "the", "device", "." ]
public unsafe class PhysicalDevice : VulkanHandle<IntPtr> { internal PhysicalDevice(IntPtr handle, Instance parent) { Handle = handle; Parent = parent; } public Instance Parent { get; } public PhysicalDeviceProperties GetProperties() { PhysicalDeviceProperties.Native native; vkGetPhysicalDeviceProperties(this, &native); PhysicalDeviceProperties.FromNative(ref native, out var properties); return properties; } public QueueFamilyProperties[] GetQueueFamilyProperties() { int count; vkGetPhysicalDeviceQueueFamilyProperties(Handle, &count, null); var queueFamilyProperties = new QueueFamilyProperties[count]; fixed (QueueFamilyProperties* queueFamilyPropertiesPtr = queueFamilyProperties) vkGetPhysicalDeviceQueueFamilyProperties(this, &count, queueFamilyPropertiesPtr); return queueFamilyProperties; } public PhysicalDeviceMemoryProperties GetMemoryProperties() { var nativeProperties = new PhysicalDeviceMemoryProperties.Native(); vkGetPhysicalDeviceMemoryProperties(this, ref nativeProperties); PhysicalDeviceMemoryProperties.FromNative(ref nativeProperties, out var properties); return properties; } public PhysicalDeviceFeatures GetFeatures() { PhysicalDeviceFeatures features; vkGetPhysicalDeviceFeatures(this, &features); return features; } public FormatProperties GetFormatProperties(Format format) { FormatProperties properties; vkGetPhysicalDeviceFormatProperties(this, format, &properties); return properties; } public ImageFormatProperties GetImageFormatProperties(Format format, ImageType type, ImageTiling tiling, ImageUsages usages, ImageCreateFlags flags = 0) { ImageFormatProperties properties; Result result = vkGetPhysicalDeviceImageFormatProperties( this, format, type, tiling, usages, flags, &properties); VulkanException.ThrowForInvalidResult(result); return properties; } public ExtensionProperties[] EnumerateExtensionProperties(string layerName = null) { int dstLayerNameByteCount = Interop.String.GetMaxByteCount(layerName); var dstLayerNamePtr = stackalloc byte[dstLayerNameByteCount]; Interop.String.ToPointer(layerName, dstLayerNamePtr, dstLayerNameByteCount); int count; Result result = vkEnumerateDeviceExtensionProperties(this, dstLayerNamePtr, &count, null); VulkanException.ThrowForInvalidResult(result); var propertiesPtr = stackalloc ExtensionProperties.Native[count]; result = vkEnumerateDeviceExtensionProperties(this, dstLayerNamePtr, &count, propertiesPtr); VulkanException.ThrowForInvalidResult(result); var properties = new ExtensionProperties[count]; for (int i = 0; i < count; i++) ExtensionProperties.FromNative(ref propertiesPtr[i], out properties[i]); return properties; } public LayerProperties[] EnumerateLayerProperties() { int count; Result result = vkEnumerateDeviceLayerProperties(this, &count, null); VulkanException.ThrowForInvalidResult(result); var nativePropertiesPtr = stackalloc LayerProperties.Native[count]; result = vkEnumerateDeviceLayerProperties(this, &count, nativePropertiesPtr); VulkanException.ThrowForInvalidResult(result); var properties = new LayerProperties[count]; for (int i = 0; i < count; i++) properties[i] = LayerProperties.FromNative(ref nativePropertiesPtr[i]); return properties; } public Device CreateDevice(DeviceCreateInfo createInfo, AllocationCallbacks? allocator = null) { return new Device(this, ref createInfo, ref allocator); } public SparseImageFormatProperties[] GetSparseImageFormatProperties( Format format, ImageType type, SampleCounts samples, ImageUsages usage, ImageTiling tiling) { int count; vkGetPhysicalDeviceSparseImageFormatProperties(this, format, type, samples, usage, tiling, &count, null); var properties = new SparseImageFormatProperties[count]; fixed (SparseImageFormatProperties* propertiesPtr = properties) vkGetPhysicalDeviceSparseImageFormatProperties(this, format, type, samples, usage, tiling, &count, propertiesPtr); return properties; } private delegate void vkGetPhysicalDevicePropertiesDelegate(IntPtr physicalDevice, PhysicalDeviceProperties.Native* properties); private static readonly vkGetPhysicalDevicePropertiesDelegate vkGetPhysicalDeviceProperties = VulkanLibrary.GetStaticProc<vkGetPhysicalDevicePropertiesDelegate>(nameof(vkGetPhysicalDeviceProperties)); private delegate void vkGetPhysicalDeviceQueueFamilyPropertiesDelegate(IntPtr physicalDevice, int* queueFamilyPropertyCount, QueueFamilyProperties* queueFamilyProperties); private static readonly vkGetPhysicalDeviceQueueFamilyPropertiesDelegate vkGetPhysicalDeviceQueueFamilyProperties = VulkanLibrary.GetStaticProc<vkGetPhysicalDeviceQueueFamilyPropertiesDelegate>(nameof(vkGetPhysicalDeviceQueueFamilyProperties)); private delegate void vkGetPhysicalDeviceMemoryPropertiesDelegate(IntPtr physicalDevice, ref PhysicalDeviceMemoryProperties.Native memoryProperties); private static readonly vkGetPhysicalDeviceMemoryPropertiesDelegate vkGetPhysicalDeviceMemoryProperties = VulkanLibrary.GetStaticProc<vkGetPhysicalDeviceMemoryPropertiesDelegate>(nameof(vkGetPhysicalDeviceMemoryProperties)); private delegate void vkGetPhysicalDeviceFeaturesDelegate(IntPtr physicalDevice, PhysicalDeviceFeatures* features); private static readonly vkGetPhysicalDeviceFeaturesDelegate vkGetPhysicalDeviceFeatures = VulkanLibrary.GetStaticProc<vkGetPhysicalDeviceFeaturesDelegate>(nameof(vkGetPhysicalDeviceFeatures)); private delegate void vkGetPhysicalDeviceFormatPropertiesDelegate(IntPtr physicalDevice, Format format, FormatProperties* formatProperties); private static readonly vkGetPhysicalDeviceFormatPropertiesDelegate vkGetPhysicalDeviceFormatProperties = VulkanLibrary.GetStaticProc<vkGetPhysicalDeviceFormatPropertiesDelegate>(nameof(vkGetPhysicalDeviceFormatProperties)); private delegate Result vkGetPhysicalDeviceImageFormatPropertiesDelegate(IntPtr physicalDevice, Format format, ImageType type, ImageTiling tiling, ImageUsages usage, ImageCreateFlags flags, ImageFormatProperties* imageFormatProperties); private static readonly vkGetPhysicalDeviceImageFormatPropertiesDelegate vkGetPhysicalDeviceImageFormatProperties = VulkanLibrary.GetStaticProc<vkGetPhysicalDeviceImageFormatPropertiesDelegate>(nameof(vkGetPhysicalDeviceImageFormatProperties)); private delegate Result vkEnumerateDeviceLayerPropertiesDelegate(IntPtr physicalDevice, int* propertyCount, LayerProperties.Native* properties); private static readonly vkEnumerateDeviceLayerPropertiesDelegate vkEnumerateDeviceLayerProperties = VulkanLibrary.GetStaticProc<vkEnumerateDeviceLayerPropertiesDelegate>(nameof(vkEnumerateDeviceLayerProperties)); private delegate Result vkEnumerateDeviceExtensionPropertiesDelegate(IntPtr physicalDevice, byte* layerName, int* propertyCount, ExtensionProperties.Native* properties); private static readonly vkEnumerateDeviceExtensionPropertiesDelegate vkEnumerateDeviceExtensionProperties = VulkanLibrary.GetStaticProc<vkEnumerateDeviceExtensionPropertiesDelegate>(nameof(vkEnumerateDeviceExtensionProperties)); private delegate void vkGetPhysicalDeviceSparseImageFormatPropertiesDelegate(IntPtr physicalDevice, Format format, ImageType type, SampleCounts samples, ImageUsages usage, ImageTiling tiling, int* propertyCount, SparseImageFormatProperties* properties); private static readonly vkGetPhysicalDeviceSparseImageFormatPropertiesDelegate vkGetPhysicalDeviceSparseImageFormatProperties = VulkanLibrary.GetStaticProc<vkGetPhysicalDeviceSparseImageFormatPropertiesDelegate>(nameof(vkGetPhysicalDeviceSparseImageFormatProperties)); }
[ "public", "unsafe", "class", "PhysicalDevice", ":", "VulkanHandle", "<", "IntPtr", ">", "{", "internal", "PhysicalDevice", "(", "IntPtr", "handle", ",", "Instance", "parent", ")", "{", "Handle", "=", "handle", ";", "Parent", "=", "parent", ";", "}", "public", "Instance", "Parent", "{", "get", ";", "}", "public", "PhysicalDeviceProperties", "GetProperties", "(", ")", "{", "PhysicalDeviceProperties", ".", "Native", "native", ";", "vkGetPhysicalDeviceProperties", "(", "this", ",", "&", "native", ")", ";", "PhysicalDeviceProperties", ".", "FromNative", "(", "ref", "native", ",", "out", "var", "properties", ")", ";", "return", "properties", ";", "}", "public", "QueueFamilyProperties", "[", "]", "GetQueueFamilyProperties", "(", ")", "{", "int", "count", ";", "vkGetPhysicalDeviceQueueFamilyProperties", "(", "Handle", ",", "&", "count", ",", "null", ")", ";", "var", "queueFamilyProperties", "=", "new", "QueueFamilyProperties", "[", "count", "]", ";", "fixed", "(", "QueueFamilyProperties", "*", "queueFamilyPropertiesPtr", "=", "queueFamilyProperties", ")", "vkGetPhysicalDeviceQueueFamilyProperties", "(", "this", ",", "&", "count", ",", "queueFamilyPropertiesPtr", ")", ";", "return", "queueFamilyProperties", ";", "}", "public", "PhysicalDeviceMemoryProperties", "GetMemoryProperties", "(", ")", "{", "var", "nativeProperties", "=", "new", "PhysicalDeviceMemoryProperties", ".", "Native", "(", ")", ";", "vkGetPhysicalDeviceMemoryProperties", "(", "this", ",", "ref", "nativeProperties", ")", ";", "PhysicalDeviceMemoryProperties", ".", "FromNative", "(", "ref", "nativeProperties", ",", "out", "var", "properties", ")", ";", "return", "properties", ";", "}", "public", "PhysicalDeviceFeatures", "GetFeatures", "(", ")", "{", "PhysicalDeviceFeatures", "features", ";", "vkGetPhysicalDeviceFeatures", "(", "this", ",", "&", "features", ")", ";", "return", "features", ";", "}", "public", "FormatProperties", "GetFormatProperties", "(", "Format", "format", ")", "{", "FormatProperties", "properties", ";", "vkGetPhysicalDeviceFormatProperties", "(", "this", ",", "format", ",", "&", "properties", ")", ";", "return", "properties", ";", "}", "public", "ImageFormatProperties", "GetImageFormatProperties", "(", "Format", "format", ",", "ImageType", "type", ",", "ImageTiling", "tiling", ",", "ImageUsages", "usages", ",", "ImageCreateFlags", "flags", "=", "0", ")", "{", "ImageFormatProperties", "properties", ";", "Result", "result", "=", "vkGetPhysicalDeviceImageFormatProperties", "(", "this", ",", "format", ",", "type", ",", "tiling", ",", "usages", ",", "flags", ",", "&", "properties", ")", ";", "VulkanException", ".", "ThrowForInvalidResult", "(", "result", ")", ";", "return", "properties", ";", "}", "public", "ExtensionProperties", "[", "]", "EnumerateExtensionProperties", "(", "string", "layerName", "=", "null", ")", "{", "int", "dstLayerNameByteCount", "=", "Interop", ".", "String", ".", "GetMaxByteCount", "(", "layerName", ")", ";", "var", "dstLayerNamePtr", "=", "stackalloc", "byte", "[", "dstLayerNameByteCount", "]", ";", "Interop", ".", "String", ".", "ToPointer", "(", "layerName", ",", "dstLayerNamePtr", ",", "dstLayerNameByteCount", ")", ";", "int", "count", ";", "Result", "result", "=", "vkEnumerateDeviceExtensionProperties", "(", "this", ",", "dstLayerNamePtr", ",", "&", "count", ",", "null", ")", ";", "VulkanException", ".", "ThrowForInvalidResult", "(", "result", ")", ";", "var", "propertiesPtr", "=", "stackalloc", "ExtensionProperties", ".", "Native", "[", "count", "]", ";", "result", "=", "vkEnumerateDeviceExtensionProperties", "(", "this", ",", "dstLayerNamePtr", ",", "&", "count", ",", "propertiesPtr", ")", ";", "VulkanException", ".", "ThrowForInvalidResult", "(", "result", ")", ";", "var", "properties", "=", "new", "ExtensionProperties", "[", "count", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "ExtensionProperties", ".", "FromNative", "(", "ref", "propertiesPtr", "[", "i", "]", ",", "out", "properties", "[", "i", "]", ")", ";", "return", "properties", ";", "}", "public", "LayerProperties", "[", "]", "EnumerateLayerProperties", "(", ")", "{", "int", "count", ";", "Result", "result", "=", "vkEnumerateDeviceLayerProperties", "(", "this", ",", "&", "count", ",", "null", ")", ";", "VulkanException", ".", "ThrowForInvalidResult", "(", "result", ")", ";", "var", "nativePropertiesPtr", "=", "stackalloc", "LayerProperties", ".", "Native", "[", "count", "]", ";", "result", "=", "vkEnumerateDeviceLayerProperties", "(", "this", ",", "&", "count", ",", "nativePropertiesPtr", ")", ";", "VulkanException", ".", "ThrowForInvalidResult", "(", "result", ")", ";", "var", "properties", "=", "new", "LayerProperties", "[", "count", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "properties", "[", "i", "]", "=", "LayerProperties", ".", "FromNative", "(", "ref", "nativePropertiesPtr", "[", "i", "]", ")", ";", "return", "properties", ";", "}", "public", "Device", "CreateDevice", "(", "DeviceCreateInfo", "createInfo", ",", "AllocationCallbacks", "?", "allocator", "=", "null", ")", "{", "return", "new", "Device", "(", "this", ",", "ref", "createInfo", ",", "ref", "allocator", ")", ";", "}", "public", "SparseImageFormatProperties", "[", "]", "GetSparseImageFormatProperties", "(", "Format", "format", ",", "ImageType", "type", ",", "SampleCounts", "samples", ",", "ImageUsages", "usage", ",", "ImageTiling", "tiling", ")", "{", "int", "count", ";", "vkGetPhysicalDeviceSparseImageFormatProperties", "(", "this", ",", "format", ",", "type", ",", "samples", ",", "usage", ",", "tiling", ",", "&", "count", ",", "null", ")", ";", "var", "properties", "=", "new", "SparseImageFormatProperties", "[", "count", "]", ";", "fixed", "(", "SparseImageFormatProperties", "*", "propertiesPtr", "=", "properties", ")", "vkGetPhysicalDeviceSparseImageFormatProperties", "(", "this", ",", "format", ",", "type", ",", "samples", ",", "usage", ",", "tiling", ",", "&", "count", ",", "propertiesPtr", ")", ";", "return", "properties", ";", "}", "private", "delegate", "void", "vkGetPhysicalDevicePropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "PhysicalDeviceProperties", ".", "Native", "*", "properties", ")", ";", "private", "static", "readonly", "vkGetPhysicalDevicePropertiesDelegate", "vkGetPhysicalDeviceProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDevicePropertiesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceProperties", ")", ")", ";", "private", "delegate", "void", "vkGetPhysicalDeviceQueueFamilyPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "int", "*", "queueFamilyPropertyCount", ",", "QueueFamilyProperties", "*", "queueFamilyProperties", ")", ";", "private", "static", "readonly", "vkGetPhysicalDeviceQueueFamilyPropertiesDelegate", "vkGetPhysicalDeviceQueueFamilyProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDeviceQueueFamilyPropertiesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceQueueFamilyProperties", ")", ")", ";", "private", "delegate", "void", "vkGetPhysicalDeviceMemoryPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "ref", "PhysicalDeviceMemoryProperties", ".", "Native", "memoryProperties", ")", ";", "private", "static", "readonly", "vkGetPhysicalDeviceMemoryPropertiesDelegate", "vkGetPhysicalDeviceMemoryProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDeviceMemoryPropertiesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceMemoryProperties", ")", ")", ";", "private", "delegate", "void", "vkGetPhysicalDeviceFeaturesDelegate", "(", "IntPtr", "physicalDevice", ",", "PhysicalDeviceFeatures", "*", "features", ")", ";", "private", "static", "readonly", "vkGetPhysicalDeviceFeaturesDelegate", "vkGetPhysicalDeviceFeatures", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDeviceFeaturesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceFeatures", ")", ")", ";", "private", "delegate", "void", "vkGetPhysicalDeviceFormatPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "Format", "format", ",", "FormatProperties", "*", "formatProperties", ")", ";", "private", "static", "readonly", "vkGetPhysicalDeviceFormatPropertiesDelegate", "vkGetPhysicalDeviceFormatProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDeviceFormatPropertiesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceFormatProperties", ")", ")", ";", "private", "delegate", "Result", "vkGetPhysicalDeviceImageFormatPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "Format", "format", ",", "ImageType", "type", ",", "ImageTiling", "tiling", ",", "ImageUsages", "usage", ",", "ImageCreateFlags", "flags", ",", "ImageFormatProperties", "*", "imageFormatProperties", ")", ";", "private", "static", "readonly", "vkGetPhysicalDeviceImageFormatPropertiesDelegate", "vkGetPhysicalDeviceImageFormatProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDeviceImageFormatPropertiesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceImageFormatProperties", ")", ")", ";", "private", "delegate", "Result", "vkEnumerateDeviceLayerPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "int", "*", "propertyCount", ",", "LayerProperties", ".", "Native", "*", "properties", ")", ";", "private", "static", "readonly", "vkEnumerateDeviceLayerPropertiesDelegate", "vkEnumerateDeviceLayerProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkEnumerateDeviceLayerPropertiesDelegate", ">", "(", "nameof", "(", "vkEnumerateDeviceLayerProperties", ")", ")", ";", "private", "delegate", "Result", "vkEnumerateDeviceExtensionPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "byte", "*", "layerName", ",", "int", "*", "propertyCount", ",", "ExtensionProperties", ".", "Native", "*", "properties", ")", ";", "private", "static", "readonly", "vkEnumerateDeviceExtensionPropertiesDelegate", "vkEnumerateDeviceExtensionProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkEnumerateDeviceExtensionPropertiesDelegate", ">", "(", "nameof", "(", "vkEnumerateDeviceExtensionProperties", ")", ")", ";", "private", "delegate", "void", "vkGetPhysicalDeviceSparseImageFormatPropertiesDelegate", "(", "IntPtr", "physicalDevice", ",", "Format", "format", ",", "ImageType", "type", ",", "SampleCounts", "samples", ",", "ImageUsages", "usage", ",", "ImageTiling", "tiling", ",", "int", "*", "propertyCount", ",", "SparseImageFormatProperties", "*", "properties", ")", ";", "private", "static", "readonly", "vkGetPhysicalDeviceSparseImageFormatPropertiesDelegate", "vkGetPhysicalDeviceSparseImageFormatProperties", "=", "VulkanLibrary", ".", "GetStaticProc", "<", "vkGetPhysicalDeviceSparseImageFormatPropertiesDelegate", ">", "(", "nameof", "(", "vkGetPhysicalDeviceSparseImageFormatProperties", ")", ")", ";", "}" ]
Opaque handle to a physical device object.
[ "Opaque", "handle", "to", "a", "physical", "device", "object", "." ]
[ "/// <summary>", "/// Gets the parent of the resource.", "/// </summary>", "/// <summary>", "/// Returns properties of a physical device.", "/// </summary>", "/// <returns>Properties of a physical device.</returns>", "/// <summary>", "/// Reports properties of the queues of the physical device.", "/// </summary>", "/// <returns>Properties of the queues of the physical device.</returns>", "/// <summary>", "/// Reports memory information for physical device.", "/// </summary>", "/// <returns>Structure in which the properties are returned.</returns>", "/// <summary>", "/// Reports capabilities of a physical device.", "/// </summary>", "/// <returns>Capabilities of a physical device.</returns>", "/// <summary>", "/// Lists physical device's format capabilities.", "/// </summary>", "/// <param name=\"format\">The format whose properties are queried.</param>", "/// <returns>Format capabilities of a physical device.</returns>", "/// <summary>", "/// Lists physical device's image format capabilities.", "/// </summary>", "/// <param name=\"format\">The image format, corresponding to <see cref=\"ImageCreateInfo.Format\"/>.</param>", "/// <param name=\"type\">The image type, corresponding to <see cref=\"ImageCreateInfo.ImageType\"/>.</param>", "/// <param name=\"tiling\">The image tiling, corresponding to <see cref=\"ImageCreateInfo.Tiling\"/>.</param>", "/// <param name=\"usages\">The intended usage of the image, corresponding to <see cref=\"ImageCreateInfo.Usage\"/>.</param>", "/// <param name=\"flags\">", "/// A bitmask describing additional parameters of the image, corresponding to <see cref=\"ImageCreateInfo.Flags\"/>.", "/// </param>", "/// <returns>Image format capabilities of a physical device</returns>", "/// <exception cref=\"VulkanException\">Vulkan returns an error code.</exception>", "/// <summary>", "/// Returns properties of available physical device extensions.", "/// </summary>", "/// <param name=\"layerName\">", "/// Is either <c>null</c> or a unicode string naming the layer to retrieve extensions from.", "/// When parameter is <c>null</c>, only extensions provided by the Vulkan implementation or", "/// by implicitly enabled layers are returned.", "/// </param>", "/// <returns>Properties of available extensions for layer.</returns>", "/// <exception cref=\"VulkanException\">Vulkan returns an error code.</exception>", "/// <summary>", "/// Returns properties of available physical device layers.", "/// </summary>", "/// <returns>Properties of available layers.</returns>", "/// <exception cref=\"VulkanException\"></exception>", "/// <summary>", "/// Create a new device instance. A logical device is created as a connection to a physical device.", "/// </summary>", "/// <param name=\"createInfo\">", "/// The structure containing information about how to create the device.", "/// </param>", "/// <param name=\"allocator\">Controls host memory allocation.</param>", "/// <returns>Device instance.</returns>", "/// <exception cref=\"VulkanException\">Vulkan returns an error code.</exception>", "/// <summary>", "/// Retrieve properties of an image format applied to sparse images.", "/// </summary>", "/// <param name=\"format\">The image format.</param>", "/// <param name=\"type\">The dimensionality of image.</param>", "/// <param name=\"samples\">The number of samples per pixel.</param>", "/// <param name=\"usage\">The intended usage of the image.</param>", "/// <param name=\"tiling\">The tiling arrangement of the data elements in memory.</param>", "/// <returns>Properties of an image format applied to sparse images.</returns>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,534
86
8490d50d91429d1c9e6855a4f7902d88326ef725
mariofusco/droolsjbpm-tools
drools-eclipse/org.guvnor.eclipse.webdav/src/client/org/eclipse/webdav/client/URLTable.java
[ "Apache-2.0" ]
Java
URLKey
/** * A <code>URLKey</code> is an equality wrapper class for * <code>URL</code>s. The wrapper treats <code>URL</code>s with and * without a trailing slash as equal. The <code>equals</code> method * works with <code>URLKey</code>s, <code>URL</code>s, and * <code>String</code>s. * <p> * <b>Note:</b> This class/interface is part of an interim API that is still under * development and expected to change significantly before reaching stability. * It is being made available at this early stage to solicit feedback from pioneering * adopters on the understanding that any code that uses this API will almost * certainly be broken (repeatedly) as the API evolves. * </p> */
A URLKey is an equality wrapper class for URLs. The wrapper treats URLs with and without a trailing slash as equal. The equals method works with URLKeys, URLs, and Strings. Note: This class/interface is part of an interim API that is still under development and expected to change significantly before reaching stability. It is being made available at this early stage to solicit feedback from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken (repeatedly) as the API evolves.
[ "A", "URLKey", "is", "an", "equality", "wrapper", "class", "for", "URLs", ".", "The", "wrapper", "treats", "URLs", "with", "and", "without", "a", "trailing", "slash", "as", "equal", ".", "The", "equals", "method", "works", "with", "URLKeys", "URLs", "and", "Strings", ".", "Note", ":", "This", "class", "/", "interface", "is", "part", "of", "an", "interim", "API", "that", "is", "still", "under", "development", "and", "expected", "to", "change", "significantly", "before", "reaching", "stability", ".", "It", "is", "being", "made", "available", "at", "this", "early", "stage", "to", "solicit", "feedback", "from", "pioneering", "adopters", "on", "the", "understanding", "that", "any", "code", "that", "uses", "this", "API", "will", "almost", "certainly", "be", "broken", "(", "repeatedly", ")", "as", "the", "API", "evolves", "." ]
class URLKey { URL url; int hashCode = -1; /** * Creates a new <code>URLKey</code> from the given <code>URL</code>. * * @param url the <code>URL</code> to wrap */ public URLKey(URL url) { this.url = url; } /** * Returns <code>true</code> if this <code>URLKey</code> is equal to the * given object. Returns <code>false</code> otherwise. The object may be * a <code>URLKey<code>, <code>String</code>, or <code>URL</code>. * * @param obj the object to compare with this <code>URLKey</code> * @return a boolean indicating whether or not this * <code>URLKey</code> is equal to the given object */ public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (obj instanceof URLKey) return equals(((URLKey) obj).getURL()); if (obj instanceof String) { try { return equals(new URL((String) obj)); } catch (MalformedURLException e) { return false; } } if (!(obj instanceof URL)) return false; if (url == (URL) obj) return true; URL url1 = URLTool.removeTrailingSlash(url); URL url2 = URLTool.removeTrailingSlash((URL) obj); return url1.equals(url2); } /** * Returns the <code>URL</code> that this <code>URLKey</code> wraps. * * @return the <code>URL</code> that this <code>URLKey</code> wraps */ public URL getURL() { return url; } /** * Returns an integer suitable for indexing this <code>URLKey</code> in * a hash table. * * @return an integer suitable for hash table indexing */ public int hashCode() { if (hashCode == -1) hashCode = URLTool.removeTrailingSlash(url).hashCode(); return hashCode; } /** * Returns this <code>URLKey</code>s <code>URL</code> as a * <code>String</code>. * * @return a string */ public String toString() { return url.toString(); } }
[ "class", "URLKey", "{", "URL", "url", ";", "int", "hashCode", "=", "-", "1", ";", "/**\n * Creates a new <code>URLKey</code> from the given <code>URL</code>.\n *\n * @param url the <code>URL</code> to wrap\n */", "public", "URLKey", "(", "URL", "url", ")", "{", "this", ".", "url", "=", "url", ";", "}", "/**\n * Returns <code>true</code> if this <code>URLKey</code> is equal to the\n * given object. Returns <code>false</code> otherwise. The object may be\n * a <code>URLKey<code>, <code>String</code>, or <code>URL</code>.\n *\n * @param obj the object to compare with this <code>URLKey</code>\n * @return a boolean indicating whether or not this\n * <code>URLKey</code> is equal to the given object\n */", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "this", "==", "obj", ")", "return", "true", ";", "if", "(", "obj", "instanceof", "URLKey", ")", "return", "equals", "(", "(", "(", "URLKey", ")", "obj", ")", ".", "getURL", "(", ")", ")", ";", "if", "(", "obj", "instanceof", "String", ")", "{", "try", "{", "return", "equals", "(", "new", "URL", "(", "(", "String", ")", "obj", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "return", "false", ";", "}", "}", "if", "(", "!", "(", "obj", "instanceof", "URL", ")", ")", "return", "false", ";", "if", "(", "url", "==", "(", "URL", ")", "obj", ")", "return", "true", ";", "URL", "url1", "=", "URLTool", ".", "removeTrailingSlash", "(", "url", ")", ";", "URL", "url2", "=", "URLTool", ".", "removeTrailingSlash", "(", "(", "URL", ")", "obj", ")", ";", "return", "url1", ".", "equals", "(", "url2", ")", ";", "}", "/**\n * Returns the <code>URL</code> that this <code>URLKey</code> wraps.\n *\n * @return the <code>URL</code> that this <code>URLKey</code> wraps\n */", "public", "URL", "getURL", "(", ")", "{", "return", "url", ";", "}", "/**\n * Returns an integer suitable for indexing this <code>URLKey</code> in\n * a hash table.\n *\n * @return an integer suitable for hash table indexing\n */", "public", "int", "hashCode", "(", ")", "{", "if", "(", "hashCode", "==", "-", "1", ")", "hashCode", "=", "URLTool", ".", "removeTrailingSlash", "(", "url", ")", ".", "hashCode", "(", ")", ";", "return", "hashCode", ";", "}", "/**\n * Returns this <code>URLKey</code>s <code>URL</code> as a\n * <code>String</code>.\n *\n * @return a string\n */", "public", "String", "toString", "(", ")", "{", "return", "url", ".", "toString", "(", ")", ";", "}", "}" ]
A <code>URLKey</code> is an equality wrapper class for <code>URL</code>s.
[ "A", "<code", ">", "URLKey<", "/", "code", ">", "is", "an", "equality", "wrapper", "class", "for", "<code", ">", "URL<", "/", "code", ">", "s", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
554
188
1671eb8f09fc5e18995dbfbc76a383b39f6c306a
roru78/ichnaea
ichnaea/data/monitor.py
[ "Apache-2.0" ]
Python
QueueSizeAndRateControl
Generate gauge metrics for queue sizes, and tune sample rate. This covers the celery task queues and the data queues. There are dynamically created export queues, with names like "export_queue_internal", or maybe "queue_export_internal", which are no longer monitored. See ichnaea/models/config.py for queue generation. The station data queues represent the backlog, and the rate controller, if enabled, attempts to keep the backlog size near a target size by adjusting the global locate sample rate.
Generate gauge metrics for queue sizes, and tune sample rate. This covers the celery task queues and the data queues. There are dynamically created export queues, with names like "export_queue_internal", or maybe "queue_export_internal", which are no longer monitored. See ichnaea/models/config.py for queue generation. The station data queues represent the backlog, and the rate controller, if enabled, attempts to keep the backlog size near a target size by adjusting the global locate sample rate.
[ "Generate", "gauge", "metrics", "for", "queue", "sizes", "and", "tune", "sample", "rate", ".", "This", "covers", "the", "celery", "task", "queues", "and", "the", "data", "queues", ".", "There", "are", "dynamically", "created", "export", "queues", "with", "names", "like", "\"", "export_queue_internal", "\"", "or", "maybe", "\"", "queue_export_internal", "\"", "which", "are", "no", "longer", "monitored", ".", "See", "ichnaea", "/", "models", "/", "config", ".", "py", "for", "queue", "generation", ".", "The", "station", "data", "queues", "represent", "the", "backlog", "and", "the", "rate", "controller", "if", "enabled", "attempts", "to", "keep", "the", "backlog", "size", "near", "a", "target", "size", "by", "adjusting", "the", "global", "locate", "sample", "rate", "." ]
class QueueSizeAndRateControl: """Generate gauge metrics for queue sizes, and tune sample rate. This covers the celery task queues and the data queues. There are dynamically created export queues, with names like "export_queue_internal", or maybe "queue_export_internal", which are no longer monitored. See ichnaea/models/config.py for queue generation. The station data queues represent the backlog, and the rate controller, if enabled, attempts to keep the backlog size near a target size by adjusting the global locate sample rate. """ def __init__(self, task): self.task = task self.rate = 0 self.rc_enabled = None self.rc_target = None self.rc_kp = None self.rc_ki = None self.rc_kd = None self.rc_state = None self.rc_controller = None def __call__(self): # Gather queue lengths, rate control settings from Redis names = list(self.task.app.all_queues.keys()) with self.task.redis_client.pipeline() as pipe: for name in names: pipe.llen(name) queue_lengths = pipe.execute() self.load_rc_params() # Emit queue metrics and calculate the station backlog backlog = 0 for name, value in zip(names, queue_lengths): tags_list = ["queue:" + name] for tag_name, tag_val in self.task.app.all_queues[name].items(): tags_list.append(f"{tag_name}:{tag_val}") if tag_name == "data_type" and tag_val in ("bluetooth", "cell", "wifi"): backlog += value METRICS.gauge("queue", value, tags=tags_list) # Use the rate controller to update the global rate if self.rc_enabled: self.run_rate_controller(backlog) rc_state = self.freeze_controller_state() with self.task.redis_client.pipeline() as pipe: pipe.set("global_locate_sample_rate", self.rate) pipe.set("rate_controller_state", rc_state) pipe.execute() METRICS.gauge("rate_control.locate.target", self.rc_target) METRICS.gauge("rate_control.locate.kp", self.rc_kp) METRICS.gauge("rate_control.locate.ki", self.rc_ki) METRICS.gauge("rate_control.locate.kd", self.rc_kd) p_term, i_term, d_term = self.rc_controller.components METRICS.gauge("rate_control.locate.pterm", p_term) METRICS.gauge("rate_control.locate.iterm", i_term) METRICS.gauge("rate_control.locate.dterm", d_term) # Emit the current (controlled or manual) global rate METRICS.gauge("rate_control.locate", self.rate) def load_rc_params(self): """Load rate controller parameters from Redis-stored strings.""" with self.task.redis_client.pipeline() as pipe: pipe.get("global_locate_sample_rate") pipe.get("rate_controller_enabled") pipe.get("rate_controller_target") pipe.get("rate_controller_kp") pipe.get("rate_controller_ki") pipe.get("rate_controller_kd") pipe.get("rate_controller_state") rate, rc_enabled, rc_target, rc_kp, rc_ki, rc_kd, rc_state = pipe.execute() try: self.rate = float(rate) except (TypeError, ValueError): self.rate = 100.0 def load_param(param_type, name, raw_value, range_check, default=None): """ Load and validate a parameter Reset invalid parameters in Redis Returns (value, is_valid) """ if raw_value is None and default is not None: self.task.redis_client.set(name, default) raw_value = default try: val = param_type(raw_value) if not range_check(val): raise ValueError("out of range") return val, True except (TypeError, ValueError): log_fmt = "Redis key '%s' has invalid value %r, disabling rate control." LOGGER.warning(log_fmt, name, raw_value) self.task.redis_client.set(name, default or 0) return None, False # Validate rate_controller_enabled, exit early if disabled self.rc_enabled, valid = load_param( int, "rate_controller_enabled", rc_enabled, lambda x: x in (0, 1) ) if not self.rc_enabled: self.task.redis_client.set("rate_controller_state", "{}") return # Validate simple PID parameters, exit if any are invalid valid = [True] * 4 self.rc_target, valid[0] = load_param( int, "rate_controller_target", rc_target, lambda x: x >= 0 ) self.rc_kp, valid[1] = load_param( float, "rate_controller_kp", rc_kp, lambda x: x >= 0, 8 ) self.rc_ki, valid[2] = load_param( float, "rate_controller_ki", rc_ki, lambda x: x >= 0, 0 ) self.rc_kd, valid[3] = load_param( float, "rate_controller_kd", rc_kd, lambda x: x >= 0, 0 ) if not all(valid): self.task.redis_client.set("rate_controller_enabled", 0) self.task.redis_client.set("rate_controller_state", "{}") self.rc_enabled = False return # State is None if new, or a JSON-encoded string try: self.rc_state = json.loads(rc_state.decode("utf8")) except AttributeError: self.rc_state = {} self.rc_controller = PID( self.rc_kp, self.rc_ki, self.rc_kd, self.rc_target, sample_time=None, output_limits=(0, self.rc_target), ) if self.rc_state.get("state") == "running": # Update controller with previous state try: p_term = self.rc_state["p_term"] i_term = self.rc_state["i_term"] d_term = self.rc_state["d_term"] last_input = self.rc_state["last_input"] last_output = self.rc_state["last_output"] last_time = self.rc_state["last_time"] except KeyError: # Skip loading state, start with fresh controller return self.rc_controller._proportional = p_term self.rc_controller._integral = i_term self.rc_controller._derivative = d_term self.rc_controller._last_input = last_input self.rc_controller._last_output = last_output self.rc_controller._last_time = last_time # Apply limits, which may clamp integral and last output self.rc_controller.output_limits = (0, self.rc_target) def run_rate_controller(self, backlog): """Generate a new sample rate.""" if not (self.rc_enabled or self.rc_controller or self.rc_state): return output = self.rc_controller(backlog) self.rate = 100.0 * max(0.0, min(1.0, output / self.rc_target)) def freeze_controller_state(self): """Convert a PID controller to a JSON encoded string.""" if self.rc_controller: p_term, i_term, d_term = self.rc_controller.components state = { "state": "running", "p_term": p_term, "i_term": i_term, "d_term": d_term, "last_output": self.rc_controller._last_output, "last_input": self.rc_controller._last_input, "last_time": self.rc_controller._last_time, } else: state = {"state": "new"} return json.dumps(state)
[ "class", "QueueSizeAndRateControl", ":", "def", "__init__", "(", "self", ",", "task", ")", ":", "self", ".", "task", "=", "task", "self", ".", "rate", "=", "0", "self", ".", "rc_enabled", "=", "None", "self", ".", "rc_target", "=", "None", "self", ".", "rc_kp", "=", "None", "self", ".", "rc_ki", "=", "None", "self", ".", "rc_kd", "=", "None", "self", ".", "rc_state", "=", "None", "self", ".", "rc_controller", "=", "None", "def", "__call__", "(", "self", ")", ":", "names", "=", "list", "(", "self", ".", "task", ".", "app", ".", "all_queues", ".", "keys", "(", ")", ")", "with", "self", ".", "task", ".", "redis_client", ".", "pipeline", "(", ")", "as", "pipe", ":", "for", "name", "in", "names", ":", "pipe", ".", "llen", "(", "name", ")", "queue_lengths", "=", "pipe", ".", "execute", "(", ")", "self", ".", "load_rc_params", "(", ")", "backlog", "=", "0", "for", "name", ",", "value", "in", "zip", "(", "names", ",", "queue_lengths", ")", ":", "tags_list", "=", "[", "\"queue:\"", "+", "name", "]", "for", "tag_name", ",", "tag_val", "in", "self", ".", "task", ".", "app", ".", "all_queues", "[", "name", "]", ".", "items", "(", ")", ":", "tags_list", ".", "append", "(", "f\"{tag_name}:{tag_val}\"", ")", "if", "tag_name", "==", "\"data_type\"", "and", "tag_val", "in", "(", "\"bluetooth\"", ",", "\"cell\"", ",", "\"wifi\"", ")", ":", "backlog", "+=", "value", "METRICS", ".", "gauge", "(", "\"queue\"", ",", "value", ",", "tags", "=", "tags_list", ")", "if", "self", ".", "rc_enabled", ":", "self", ".", "run_rate_controller", "(", "backlog", ")", "rc_state", "=", "self", ".", "freeze_controller_state", "(", ")", "with", "self", ".", "task", ".", "redis_client", ".", "pipeline", "(", ")", "as", "pipe", ":", "pipe", ".", "set", "(", "\"global_locate_sample_rate\"", ",", "self", ".", "rate", ")", "pipe", ".", "set", "(", "\"rate_controller_state\"", ",", "rc_state", ")", "pipe", ".", "execute", "(", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate.target\"", ",", "self", ".", "rc_target", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate.kp\"", ",", "self", ".", "rc_kp", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate.ki\"", ",", "self", ".", "rc_ki", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate.kd\"", ",", "self", ".", "rc_kd", ")", "p_term", ",", "i_term", ",", "d_term", "=", "self", ".", "rc_controller", ".", "components", "METRICS", ".", "gauge", "(", "\"rate_control.locate.pterm\"", ",", "p_term", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate.iterm\"", ",", "i_term", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate.dterm\"", ",", "d_term", ")", "METRICS", ".", "gauge", "(", "\"rate_control.locate\"", ",", "self", ".", "rate", ")", "def", "load_rc_params", "(", "self", ")", ":", "\"\"\"Load rate controller parameters from Redis-stored strings.\"\"\"", "with", "self", ".", "task", ".", "redis_client", ".", "pipeline", "(", ")", "as", "pipe", ":", "pipe", ".", "get", "(", "\"global_locate_sample_rate\"", ")", "pipe", ".", "get", "(", "\"rate_controller_enabled\"", ")", "pipe", ".", "get", "(", "\"rate_controller_target\"", ")", "pipe", ".", "get", "(", "\"rate_controller_kp\"", ")", "pipe", ".", "get", "(", "\"rate_controller_ki\"", ")", "pipe", ".", "get", "(", "\"rate_controller_kd\"", ")", "pipe", ".", "get", "(", "\"rate_controller_state\"", ")", "rate", ",", "rc_enabled", ",", "rc_target", ",", "rc_kp", ",", "rc_ki", ",", "rc_kd", ",", "rc_state", "=", "pipe", ".", "execute", "(", ")", "try", ":", "self", ".", "rate", "=", "float", "(", "rate", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "self", ".", "rate", "=", "100.0", "def", "load_param", "(", "param_type", ",", "name", ",", "raw_value", ",", "range_check", ",", "default", "=", "None", ")", ":", "\"\"\"\n Load and validate a parameter\n\n Reset invalid parameters in Redis\n Returns (value, is_valid)\n \"\"\"", "if", "raw_value", "is", "None", "and", "default", "is", "not", "None", ":", "self", ".", "task", ".", "redis_client", ".", "set", "(", "name", ",", "default", ")", "raw_value", "=", "default", "try", ":", "val", "=", "param_type", "(", "raw_value", ")", "if", "not", "range_check", "(", "val", ")", ":", "raise", "ValueError", "(", "\"out of range\"", ")", "return", "val", ",", "True", "except", "(", "TypeError", ",", "ValueError", ")", ":", "log_fmt", "=", "\"Redis key '%s' has invalid value %r, disabling rate control.\"", "LOGGER", ".", "warning", "(", "log_fmt", ",", "name", ",", "raw_value", ")", "self", ".", "task", ".", "redis_client", ".", "set", "(", "name", ",", "default", "or", "0", ")", "return", "None", ",", "False", "self", ".", "rc_enabled", ",", "valid", "=", "load_param", "(", "int", ",", "\"rate_controller_enabled\"", ",", "rc_enabled", ",", "lambda", "x", ":", "x", "in", "(", "0", ",", "1", ")", ")", "if", "not", "self", ".", "rc_enabled", ":", "self", ".", "task", ".", "redis_client", ".", "set", "(", "\"rate_controller_state\"", ",", "\"{}\"", ")", "return", "valid", "=", "[", "True", "]", "*", "4", "self", ".", "rc_target", ",", "valid", "[", "0", "]", "=", "load_param", "(", "int", ",", "\"rate_controller_target\"", ",", "rc_target", ",", "lambda", "x", ":", "x", ">=", "0", ")", "self", ".", "rc_kp", ",", "valid", "[", "1", "]", "=", "load_param", "(", "float", ",", "\"rate_controller_kp\"", ",", "rc_kp", ",", "lambda", "x", ":", "x", ">=", "0", ",", "8", ")", "self", ".", "rc_ki", ",", "valid", "[", "2", "]", "=", "load_param", "(", "float", ",", "\"rate_controller_ki\"", ",", "rc_ki", ",", "lambda", "x", ":", "x", ">=", "0", ",", "0", ")", "self", ".", "rc_kd", ",", "valid", "[", "3", "]", "=", "load_param", "(", "float", ",", "\"rate_controller_kd\"", ",", "rc_kd", ",", "lambda", "x", ":", "x", ">=", "0", ",", "0", ")", "if", "not", "all", "(", "valid", ")", ":", "self", ".", "task", ".", "redis_client", ".", "set", "(", "\"rate_controller_enabled\"", ",", "0", ")", "self", ".", "task", ".", "redis_client", ".", "set", "(", "\"rate_controller_state\"", ",", "\"{}\"", ")", "self", ".", "rc_enabled", "=", "False", "return", "try", ":", "self", ".", "rc_state", "=", "json", ".", "loads", "(", "rc_state", ".", "decode", "(", "\"utf8\"", ")", ")", "except", "AttributeError", ":", "self", ".", "rc_state", "=", "{", "}", "self", ".", "rc_controller", "=", "PID", "(", "self", ".", "rc_kp", ",", "self", ".", "rc_ki", ",", "self", ".", "rc_kd", ",", "self", ".", "rc_target", ",", "sample_time", "=", "None", ",", "output_limits", "=", "(", "0", ",", "self", ".", "rc_target", ")", ",", ")", "if", "self", ".", "rc_state", ".", "get", "(", "\"state\"", ")", "==", "\"running\"", ":", "try", ":", "p_term", "=", "self", ".", "rc_state", "[", "\"p_term\"", "]", "i_term", "=", "self", ".", "rc_state", "[", "\"i_term\"", "]", "d_term", "=", "self", ".", "rc_state", "[", "\"d_term\"", "]", "last_input", "=", "self", ".", "rc_state", "[", "\"last_input\"", "]", "last_output", "=", "self", ".", "rc_state", "[", "\"last_output\"", "]", "last_time", "=", "self", ".", "rc_state", "[", "\"last_time\"", "]", "except", "KeyError", ":", "return", "self", ".", "rc_controller", ".", "_proportional", "=", "p_term", "self", ".", "rc_controller", ".", "_integral", "=", "i_term", "self", ".", "rc_controller", ".", "_derivative", "=", "d_term", "self", ".", "rc_controller", ".", "_last_input", "=", "last_input", "self", ".", "rc_controller", ".", "_last_output", "=", "last_output", "self", ".", "rc_controller", ".", "_last_time", "=", "last_time", "self", ".", "rc_controller", ".", "output_limits", "=", "(", "0", ",", "self", ".", "rc_target", ")", "def", "run_rate_controller", "(", "self", ",", "backlog", ")", ":", "\"\"\"Generate a new sample rate.\"\"\"", "if", "not", "(", "self", ".", "rc_enabled", "or", "self", ".", "rc_controller", "or", "self", ".", "rc_state", ")", ":", "return", "output", "=", "self", ".", "rc_controller", "(", "backlog", ")", "self", ".", "rate", "=", "100.0", "*", "max", "(", "0.0", ",", "min", "(", "1.0", ",", "output", "/", "self", ".", "rc_target", ")", ")", "def", "freeze_controller_state", "(", "self", ")", ":", "\"\"\"Convert a PID controller to a JSON encoded string.\"\"\"", "if", "self", ".", "rc_controller", ":", "p_term", ",", "i_term", ",", "d_term", "=", "self", ".", "rc_controller", ".", "components", "state", "=", "{", "\"state\"", ":", "\"running\"", ",", "\"p_term\"", ":", "p_term", ",", "\"i_term\"", ":", "i_term", ",", "\"d_term\"", ":", "d_term", ",", "\"last_output\"", ":", "self", ".", "rc_controller", ".", "_last_output", ",", "\"last_input\"", ":", "self", ".", "rc_controller", ".", "_last_input", ",", "\"last_time\"", ":", "self", ".", "rc_controller", ".", "_last_time", ",", "}", "else", ":", "state", "=", "{", "\"state\"", ":", "\"new\"", "}", "return", "json", ".", "dumps", "(", "state", ")" ]
Generate gauge metrics for queue sizes, and tune sample rate.
[ "Generate", "gauge", "metrics", "for", "queue", "sizes", "and", "tune", "sample", "rate", "." ]
[ "\"\"\"Generate gauge metrics for queue sizes, and tune sample rate.\n\n This covers the celery task queues and the data queues.\n\n There are dynamically created export queues, with names like\n \"export_queue_internal\", or maybe \"queue_export_internal\", which are no\n longer monitored. See ichnaea/models/config.py for queue generation.\n\n The station data queues represent the backlog, and the rate controller,\n if enabled, attempts to keep the backlog size near a target size by\n adjusting the global locate sample rate.\n \"\"\"", "# Gather queue lengths, rate control settings from Redis", "# Emit queue metrics and calculate the station backlog", "# Use the rate controller to update the global rate", "# Emit the current (controlled or manual) global rate", "\"\"\"Load rate controller parameters from Redis-stored strings.\"\"\"", "\"\"\"\n Load and validate a parameter\n\n Reset invalid parameters in Redis\n Returns (value, is_valid)\n \"\"\"", "# Validate rate_controller_enabled, exit early if disabled", "# Validate simple PID parameters, exit if any are invalid", "# State is None if new, or a JSON-encoded string", "# Update controller with previous state", "# Skip loading state, start with fresh controller", "# Apply limits, which may clamp integral and last output", "\"\"\"Generate a new sample rate.\"\"\"", "\"\"\"Convert a PID controller to a JSON encoded string.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,692
107
37a64ea58b5df421eac40f9840d5366d8ad8966c
blueww/azure-sdk-for-node
lib/services/batch/lib/models/jobPreparationTask.js
[ "Apache-2.0", "MIT" ]
JavaScript
JobPreparationTask
/** * @summary A Job Preparation task to run before any tasks of the job on any * given compute node. * * You can use Job Preparation to prepare a compute node to run tasks for the * job. Activities commonly performed in Job Preparation include: Downloading * common resource files used by all the tasks in the job. The Job Preparation * task can download these common resource files to the shared location on the * compute node. (AZ_BATCH_NODE_ROOT_DIR\shared), or starting a local service * on the compute node so that all tasks of that job can communicate with it. * If the Job Preparation task fails (that is, exhausts its retry count before * exiting with exit code 0), Batch will not run tasks of this job on the * compute node. The node remains ineligible to run tasks of this job until it * is reimaged. The node remains active and can be used for other jobs. The Job * Preparation task can run multiple times on the same compute node. Therefore, * you should write the Job Preparation task to handle re-execution. If the * compute node is rebooted, the Job Preparation task is run again on the node * before scheduling any other task of the job, if * rerunOnNodeRebootAfterSuccess is true or if the Job Preparation task did not * previously complete. If the compute node is reimaged, the Job Preparation * task is run again before scheduling any task of the job. * */
@summary A Job Preparation task to run before any tasks of the job on any given compute node. You can use Job Preparation to prepare a compute node to run tasks for the job. Activities commonly performed in Job Preparation include: Downloading common resource files used by all the tasks in the job. The Job Preparation task can download these common resource files to the shared location on the compute node. (AZ_BATCH_NODE_ROOT_DIR\shared), or starting a local service on the compute node so that all tasks of that job can communicate with it. If the Job Preparation task fails (that is, exhausts its retry count before exiting with exit code 0), Batch will not run tasks of this job on the compute node. The node remains ineligible to run tasks of this job until it is reimaged. The node remains active and can be used for other jobs. The Job Preparation task can run multiple times on the same compute node. Therefore, you should write the Job Preparation task to handle re-execution. If the compute node is rebooted, the Job Preparation task is run again on the node before scheduling any other task of the job, if rerunOnNodeRebootAfterSuccess is true or if the Job Preparation task did not previously complete. If the compute node is reimaged, the Job Preparation task is run again before scheduling any task of the job.
[ "@summary", "A", "Job", "Preparation", "task", "to", "run", "before", "any", "tasks", "of", "the", "job", "on", "any", "given", "compute", "node", ".", "You", "can", "use", "Job", "Preparation", "to", "prepare", "a", "compute", "node", "to", "run", "tasks", "for", "the", "job", ".", "Activities", "commonly", "performed", "in", "Job", "Preparation", "include", ":", "Downloading", "common", "resource", "files", "used", "by", "all", "the", "tasks", "in", "the", "job", ".", "The", "Job", "Preparation", "task", "can", "download", "these", "common", "resource", "files", "to", "the", "shared", "location", "on", "the", "compute", "node", ".", "(", "AZ_BATCH_NODE_ROOT_DIR", "\\", "shared", ")", "or", "starting", "a", "local", "service", "on", "the", "compute", "node", "so", "that", "all", "tasks", "of", "that", "job", "can", "communicate", "with", "it", ".", "If", "the", "Job", "Preparation", "task", "fails", "(", "that", "is", "exhausts", "its", "retry", "count", "before", "exiting", "with", "exit", "code", "0", ")", "Batch", "will", "not", "run", "tasks", "of", "this", "job", "on", "the", "compute", "node", ".", "The", "node", "remains", "ineligible", "to", "run", "tasks", "of", "this", "job", "until", "it", "is", "reimaged", ".", "The", "node", "remains", "active", "and", "can", "be", "used", "for", "other", "jobs", ".", "The", "Job", "Preparation", "task", "can", "run", "multiple", "times", "on", "the", "same", "compute", "node", ".", "Therefore", "you", "should", "write", "the", "Job", "Preparation", "task", "to", "handle", "re", "-", "execution", ".", "If", "the", "compute", "node", "is", "rebooted", "the", "Job", "Preparation", "task", "is", "run", "again", "on", "the", "node", "before", "scheduling", "any", "other", "task", "of", "the", "job", "if", "rerunOnNodeRebootAfterSuccess", "is", "true", "or", "if", "the", "Job", "Preparation", "task", "did", "not", "previously", "complete", ".", "If", "the", "compute", "node", "is", "reimaged", "the", "Job", "Preparation", "task", "is", "run", "again", "before", "scheduling", "any", "task", "of", "the", "job", "." ]
class JobPreparationTask { /** * Create a JobPreparationTask. * @member {string} [id] A string that uniquely identifies the Job * Preparation task within the job. The ID can contain any combination of * alphanumeric characters including hyphens and underscores and cannot * contain more than 64 characters. If you do not specify this property, the * Batch service assigns a default value of 'jobpreparation'. No other task * in the job can have the same ID as the Job Preparation task. If you try to * submit a task with the same id, the Batch service rejects the request with * error code TaskIdSameAsJobPreparationTask; if you are calling the REST API * directly, the HTTP status code is 409 (Conflict). * @member {string} commandLine The command line of the Job Preparation task. * The command line does not run under a shell, and therefore cannot take * advantage of shell features such as environment variable expansion. If you * want to take advantage of such features, you should invoke the shell in * the command line, for example using "cmd /c MyCommand" in Windows or * "/bin/sh -c MyCommand" in Linux. * @member {object} [containerSettings] The settings for the container under * which the Job Preparation task runs. When this is specified, all * directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of * Azure Batch directories on the node) are mapped into the container, all * task environment variables are mapped into the container, and the task * command line is executed in the container. * @member {string} [containerSettings.containerRunOptions] These additional * options are supplied as arguments to the "docker create" command, in * addition to those controlled by the Batch Service. * @member {string} [containerSettings.imageName] This is the full image * reference, as would be specified to "docker pull". If no tag is provided * as part of the image name, the tag ":latest" is used as a default. * @member {object} [containerSettings.registry] This setting can be omitted * if was already provided at pool creation. * @member {string} [containerSettings.registry.registryServer] If omitted, * the default is "docker.io". * @member {string} [containerSettings.registry.userName] * @member {string} [containerSettings.registry.password] * @member {array} [resourceFiles] A list of files that the Batch service * will download to the compute node before running the command line. Files * listed under this element are located in the task's working directory. * @member {array} [environmentSettings] A list of environment variable * settings for the Job Preparation task. * @member {object} [constraints] Constraints that apply to the Job * Preparation task. * @member {moment.duration} [constraints.maxWallClockTime] If this is not * specified, there is no time limit on how long the task may run. * @member {moment.duration} [constraints.retentionTime] The default is * infinite, i.e. the task directory will be retained until the compute node * is removed or reimaged. * @member {number} [constraints.maxTaskRetryCount] Note that this value * specifically controls the number of retries. The Batch service will try * the task once, and may then retry up to this limit. For example, if the * maximum retry count is 3, Batch tries the task up to 4 times (one initial * try and 3 retries). If the maximum retry count is 0, the Batch service * does not retry the task. If the maximum retry count is -1, the Batch * service retries the task without limit. * @member {boolean} [waitForSuccess] Whether the Batch service should wait * for the Job Preparation task to complete successfully before scheduling * any other tasks of the job on the compute node. A Job Preparation task has * completed successfully if it exits with exit code 0. If true and the Job * Preparation task fails on a compute node, the Batch service retries the * Job Preparation task up to its maximum retry count (as specified in the * constraints element). If the task has still not completed successfully * after all retries, then the Batch service will not schedule tasks of the * job to the compute node. The compute node remains active and eligible to * run tasks of other jobs. If false, the Batch service will not wait for the * Job Preparation task to complete. In this case, other tasks of the job can * start executing on the compute node while the Job Preparation task is * still running; and even if the Job Preparation task fails, new tasks will * continue to be scheduled on the node. The default value is true. * @member {object} [userIdentity] The user identity under which the Job * Preparation task runs. If omitted, the task runs as a non-administrative * user unique to the task on Windows nodes, or a a non-administrative user * unique to the pool on Linux nodes. * @member {string} [userIdentity.userName] The userName and autoUser * properties are mutually exclusive; you must specify one but not both. * @member {object} [userIdentity.autoUser] The userName and autoUser * properties are mutually exclusive; you must specify one but not both. * @member {string} [userIdentity.autoUser.scope] Values are: * * pool - specifies that the task runs as the common auto user account which * is created on every node in a pool. * task - specifies that the service should create a new user for the task. * The default value is task. Possible values include: 'task', 'pool' * @member {string} [userIdentity.autoUser.elevationLevel] nonAdmin - The * auto user is a standard user without elevated access. admin - The auto * user is a user with elevated access and operates with full Administrator * permissions. The default value is nonAdmin. Possible values include: * 'nonAdmin', 'admin' * @member {boolean} [rerunOnNodeRebootAfterSuccess] Whether the Batch * service should rerun the Job Preparation task after a compute node * reboots. The Job Preparation task is always rerun if a compute node is * reimaged, or if the Job Preparation task did not complete (e.g. because * the reboot occurred while the task was running). Therefore, you should * always write a Job Preparation task to be idempotent and to behave * correctly if run multiple times. The default value is true. */ constructor() { } /** * Defines the metadata of JobPreparationTask * * @returns {object} metadata of JobPreparationTask * */ mapper() { return { required: false, serializedName: 'JobPreparationTask', type: { name: 'Composite', className: 'JobPreparationTask', modelProperties: { id: { required: false, serializedName: 'id', type: { name: 'String' } }, commandLine: { required: true, serializedName: 'commandLine', type: { name: 'String' } }, containerSettings: { required: false, serializedName: 'containerSettings', type: { name: 'Composite', className: 'TaskContainerSettings' } }, resourceFiles: { required: false, serializedName: 'resourceFiles', type: { name: 'Sequence', element: { required: false, serializedName: 'ResourceFileElementType', type: { name: 'Composite', className: 'ResourceFile' } } } }, environmentSettings: { required: false, serializedName: 'environmentSettings', type: { name: 'Sequence', element: { required: false, serializedName: 'EnvironmentSettingElementType', type: { name: 'Composite', className: 'EnvironmentSetting' } } } }, constraints: { required: false, serializedName: 'constraints', type: { name: 'Composite', className: 'TaskConstraints' } }, waitForSuccess: { required: false, serializedName: 'waitForSuccess', type: { name: 'Boolean' } }, userIdentity: { required: false, serializedName: 'userIdentity', type: { name: 'Composite', className: 'UserIdentity' } }, rerunOnNodeRebootAfterSuccess: { required: false, serializedName: 'rerunOnNodeRebootAfterSuccess', type: { name: 'Boolean' } } } } }; } }
[ "class", "JobPreparationTask", "{", "constructor", "(", ")", "{", "}", "mapper", "(", ")", "{", "return", "{", "required", ":", "false", ",", "serializedName", ":", "'JobPreparationTask'", ",", "type", ":", "{", "name", ":", "'Composite'", ",", "className", ":", "'JobPreparationTask'", ",", "modelProperties", ":", "{", "id", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'id'", ",", "type", ":", "{", "name", ":", "'String'", "}", "}", ",", "commandLine", ":", "{", "required", ":", "true", ",", "serializedName", ":", "'commandLine'", ",", "type", ":", "{", "name", ":", "'String'", "}", "}", ",", "containerSettings", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'containerSettings'", ",", "type", ":", "{", "name", ":", "'Composite'", ",", "className", ":", "'TaskContainerSettings'", "}", "}", ",", "resourceFiles", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'resourceFiles'", ",", "type", ":", "{", "name", ":", "'Sequence'", ",", "element", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'ResourceFileElementType'", ",", "type", ":", "{", "name", ":", "'Composite'", ",", "className", ":", "'ResourceFile'", "}", "}", "}", "}", ",", "environmentSettings", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'environmentSettings'", ",", "type", ":", "{", "name", ":", "'Sequence'", ",", "element", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'EnvironmentSettingElementType'", ",", "type", ":", "{", "name", ":", "'Composite'", ",", "className", ":", "'EnvironmentSetting'", "}", "}", "}", "}", ",", "constraints", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'constraints'", ",", "type", ":", "{", "name", ":", "'Composite'", ",", "className", ":", "'TaskConstraints'", "}", "}", ",", "waitForSuccess", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'waitForSuccess'", ",", "type", ":", "{", "name", ":", "'Boolean'", "}", "}", ",", "userIdentity", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'userIdentity'", ",", "type", ":", "{", "name", ":", "'Composite'", ",", "className", ":", "'UserIdentity'", "}", "}", ",", "rerunOnNodeRebootAfterSuccess", ":", "{", "required", ":", "false", ",", "serializedName", ":", "'rerunOnNodeRebootAfterSuccess'", ",", "type", ":", "{", "name", ":", "'Boolean'", "}", "}", "}", "}", "}", ";", "}", "}" ]
@summary A Job Preparation task to run before any tasks of the job on any given compute node.
[ "@summary", "A", "Job", "Preparation", "task", "to", "run", "before", "any", "tasks", "of", "the", "job", "on", "any", "given", "compute", "node", "." ]
[ "/**\n * Create a JobPreparationTask.\n * @member {string} [id] A string that uniquely identifies the Job\n * Preparation task within the job. The ID can contain any combination of\n * alphanumeric characters including hyphens and underscores and cannot\n * contain more than 64 characters. If you do not specify this property, the\n * Batch service assigns a default value of 'jobpreparation'. No other task\n * in the job can have the same ID as the Job Preparation task. If you try to\n * submit a task with the same id, the Batch service rejects the request with\n * error code TaskIdSameAsJobPreparationTask; if you are calling the REST API\n * directly, the HTTP status code is 409 (Conflict).\n * @member {string} commandLine The command line of the Job Preparation task.\n * The command line does not run under a shell, and therefore cannot take\n * advantage of shell features such as environment variable expansion. If you\n * want to take advantage of such features, you should invoke the shell in\n * the command line, for example using \"cmd /c MyCommand\" in Windows or\n * \"/bin/sh -c MyCommand\" in Linux.\n * @member {object} [containerSettings] The settings for the container under\n * which the Job Preparation task runs. When this is specified, all\n * directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of\n * Azure Batch directories on the node) are mapped into the container, all\n * task environment variables are mapped into the container, and the task\n * command line is executed in the container.\n * @member {string} [containerSettings.containerRunOptions] These additional\n * options are supplied as arguments to the \"docker create\" command, in\n * addition to those controlled by the Batch Service.\n * @member {string} [containerSettings.imageName] This is the full image\n * reference, as would be specified to \"docker pull\". If no tag is provided\n * as part of the image name, the tag \":latest\" is used as a default.\n * @member {object} [containerSettings.registry] This setting can be omitted\n * if was already provided at pool creation.\n * @member {string} [containerSettings.registry.registryServer] If omitted,\n * the default is \"docker.io\".\n * @member {string} [containerSettings.registry.userName]\n * @member {string} [containerSettings.registry.password]\n * @member {array} [resourceFiles] A list of files that the Batch service\n * will download to the compute node before running the command line. Files\n * listed under this element are located in the task's working directory.\n * @member {array} [environmentSettings] A list of environment variable\n * settings for the Job Preparation task.\n * @member {object} [constraints] Constraints that apply to the Job\n * Preparation task.\n * @member {moment.duration} [constraints.maxWallClockTime] If this is not\n * specified, there is no time limit on how long the task may run.\n * @member {moment.duration} [constraints.retentionTime] The default is\n * infinite, i.e. the task directory will be retained until the compute node\n * is removed or reimaged.\n * @member {number} [constraints.maxTaskRetryCount] Note that this value\n * specifically controls the number of retries. The Batch service will try\n * the task once, and may then retry up to this limit. For example, if the\n * maximum retry count is 3, Batch tries the task up to 4 times (one initial\n * try and 3 retries). If the maximum retry count is 0, the Batch service\n * does not retry the task. If the maximum retry count is -1, the Batch\n * service retries the task without limit.\n * @member {boolean} [waitForSuccess] Whether the Batch service should wait\n * for the Job Preparation task to complete successfully before scheduling\n * any other tasks of the job on the compute node. A Job Preparation task has\n * completed successfully if it exits with exit code 0. If true and the Job\n * Preparation task fails on a compute node, the Batch service retries the\n * Job Preparation task up to its maximum retry count (as specified in the\n * constraints element). If the task has still not completed successfully\n * after all retries, then the Batch service will not schedule tasks of the\n * job to the compute node. The compute node remains active and eligible to\n * run tasks of other jobs. If false, the Batch service will not wait for the\n * Job Preparation task to complete. In this case, other tasks of the job can\n * start executing on the compute node while the Job Preparation task is\n * still running; and even if the Job Preparation task fails, new tasks will\n * continue to be scheduled on the node. The default value is true.\n * @member {object} [userIdentity] The user identity under which the Job\n * Preparation task runs. If omitted, the task runs as a non-administrative\n * user unique to the task on Windows nodes, or a a non-administrative user\n * unique to the pool on Linux nodes.\n * @member {string} [userIdentity.userName] The userName and autoUser\n * properties are mutually exclusive; you must specify one but not both.\n * @member {object} [userIdentity.autoUser] The userName and autoUser\n * properties are mutually exclusive; you must specify one but not both.\n * @member {string} [userIdentity.autoUser.scope] Values are:\n *\n * pool - specifies that the task runs as the common auto user account which\n * is created on every node in a pool.\n * task - specifies that the service should create a new user for the task.\n * The default value is task. Possible values include: 'task', 'pool'\n * @member {string} [userIdentity.autoUser.elevationLevel] nonAdmin - The\n * auto user is a standard user without elevated access. admin - The auto\n * user is a user with elevated access and operates with full Administrator\n * permissions. The default value is nonAdmin. Possible values include:\n * 'nonAdmin', 'admin'\n * @member {boolean} [rerunOnNodeRebootAfterSuccess] Whether the Batch\n * service should rerun the Job Preparation task after a compute node\n * reboots. The Job Preparation task is always rerun if a compute node is\n * reimaged, or if the Job Preparation task did not complete (e.g. because\n * the reboot occurred while the task was running). Therefore, you should\n * always write a Job Preparation task to be idempotent and to behave\n * correctly if run multiple times. The default value is true.\n */", "/**\n * Defines the metadata of JobPreparationTask\n *\n * @returns {object} metadata of JobPreparationTask\n *\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
2,007
312
4e4a4c93176636d18aa42d54585645e345a45880
harrywsh/hackx-holokit
Assets/AppleLocalMultiplayer/Source/UNetSupport/AppleLocalMultiplayerNetworkManagerHelper.cs
[ "Apache-2.0" ]
C#
AppleLocalMultiplayerNetworkManagerHelper
/// <summary> /// A helper class that works in conjunction with <see cref="NetworkManager"/>. /// It automatically manages showing the device picker /// and correctly handling the local multiplayer session. /// </summary> /// <example> /// The NetworkManager.Start* family of methods is mirrored, just use this class /// instead of using NetworkManager directly to start your client/server/host. /// </example>
A helper class that works in conjunction with . It automatically manages showing the device picker and correctly handling the local multiplayer session.
[ "A", "helper", "class", "that", "works", "in", "conjunction", "with", ".", "It", "automatically", "manages", "showing", "the", "device", "picker", "and", "correctly", "handling", "the", "local", "multiplayer", "session", "." ]
[RequireComponent(typeof(NetworkManager))] public class AppleLocalMultiplayerNetworkManagerHelper : MonoBehaviour { [SerializeField] protected LocalMultiplayerNetworkManagerSettings _multipeerConnectivitySettings = new LocalMultiplayerNetworkManagerSettings(); [SerializeField] [HideInInspector] protected NetworkManager _networkManager; #if UNITY_IOS || UNITY_TVOS || UNITY_STANDALONE_OSX private MultiplayerMode _desiredMode = MultiplayerMode.None; private Action _clientAction; private Action _hostAction; private PeerId _serverPeerId; private ICustomDeviceBrowser _customDeviceBrowser; public bool IsInitialized { get; private set; } public IDictionary<string, string> DiscoveryInfo { get; set; } private void OnEnable() { _networkManager = GetComponent<NetworkManager>(); try { AppleLocalMultiplayer.Session.SetServiceType(_multipeerConnectivitySettings.ServiceType); IsInitialized = true; } catch (Exception e) { Debug.LogException(e); } AppleLocalMultiplayer.Session.PeerStateChanged += OnSessionPeerStateChanged; AppleLocalMultiplayer.Session.Started += OnSessionStarted; AppleLocalMultiplayer.Session.Stopped += OnSessionStopped; AppleLocalMultiplayer.CustomPeerDiscovery.PeerFound += OnCustomPeerDiscoveryPeerFound; AppleLocalMultiplayer.CustomPeerDiscovery.PeerLost += OnCustomPeerDiscoveryPeerLost; AppleLocalMultiplayer.CustomPeerDiscovery.StartFailed += OnCustomPeerDiscoveryStartFailed; AppleLocalMultiplayer.PeerDiscovery.NearbyPeerPresenting += OnPeerDiscoveryNearbyPeerPresenting; AppleLocalMultiplayer.PeerDiscovery.Cancelled += OnPeerDiscoveryCancelled; AppleLocalMultiplayer.PeerDiscovery.Finished += OnPeerDiscoveryFinished; AppleLocalMultiplayer.CustomServiceAdvertiser.InvitationReceived += OnCustomServiceAdvertiserInvitationReceived; AppleLocalMultiplayer.CustomServiceAdvertiser.StartFailed += OnCustomServiceAdvertiserStartFailed; AppleLocalMultiplayer.ServiceAdvertiser.InvitationDismissed += OnServiceAdvertiserInvitationDismissed; AppleLocalMultiplayer.ServiceAdvertiser.InvitationPresenting += OnServiceAdvertiserInvitationPresenting; } private void OnDisable() { AppleLocalMultiplayer.Session.PeerStateChanged -= OnSessionPeerStateChanged; AppleLocalMultiplayer.Session.Started -= OnSessionStarted; AppleLocalMultiplayer.Session.Stopped -= OnSessionStopped; AppleLocalMultiplayer.CustomPeerDiscovery.PeerFound -= OnCustomPeerDiscoveryPeerFound; AppleLocalMultiplayer.CustomPeerDiscovery.PeerLost -= OnCustomPeerDiscoveryPeerLost; AppleLocalMultiplayer.CustomPeerDiscovery.StartFailed -= OnCustomPeerDiscoveryStartFailed; AppleLocalMultiplayer.PeerDiscovery.NearbyPeerPresenting -= OnPeerDiscoveryNearbyPeerPresenting; AppleLocalMultiplayer.PeerDiscovery.Cancelled -= OnPeerDiscoveryCancelled; AppleLocalMultiplayer.PeerDiscovery.Finished -= OnPeerDiscoveryFinished; AppleLocalMultiplayer.CustomServiceAdvertiser.InvitationReceived -= OnCustomServiceAdvertiserInvitationReceived; AppleLocalMultiplayer.CustomServiceAdvertiser.StartFailed -= OnCustomServiceAdvertiserStartFailed; AppleLocalMultiplayer.ServiceAdvertiser.InvitationDismissed -= OnServiceAdvertiserInvitationDismissed; AppleLocalMultiplayer.ServiceAdvertiser.InvitationPresenting -= OnServiceAdvertiserInvitationPresenting; } public void SetCustomDeviceBrowser(ICustomDeviceBrowser customDeviceBrowser) { if (_customDeviceBrowser != null) { _customDeviceBrowser.OnPeerPicked -= OnPeerPicked; } _customDeviceBrowser = customDeviceBrowser; if (_customDeviceBrowser != null) { _customDeviceBrowser.OnPeerPicked += OnPeerPicked; } } private void StartLocalMultiplayerClient(Action onReadyAction) { _clientAction = onReadyAction; _serverPeerId = null; _desiredMode = MultiplayerMode.Client; StartSession(); if (_customDeviceBrowser != null) { _customDeviceBrowser.Open(); } else { AppleLocalMultiplayer.PeerDiscovery.OpenBrowser(); } } private void StartLocalMultiplayerHost(Action onReadyAction) { _hostAction = onReadyAction; _desiredMode = MultiplayerMode.Host; StartSession(); AppleLocalMultiplayer.ServiceAdvertiser.StartAdvertising(DiscoveryInfo); if (_hostAction != null) { _hostAction(); _hostAction = null; } } private void StopAll() { AppleLocalMultiplayer.ServiceAdvertiser.StopAdvertising(); _networkManager.StopHost(); _serverPeerId = null; _desiredMode = MultiplayerMode.None; } private void StartSession() { AppleLocalMultiplayer.Session.SetServerPort(_networkManager.networkPort); AppleLocalMultiplayer.Session.StartSession(); } private void OnPeerPicked(PeerId peerId) { AppleLocalMultiplayer.CustomPeerDiscovery.InvitePeer(peerId); if (_customDeviceBrowser != null) { _customDeviceBrowser.Close(); } } #region NetworkManager methods public void StartClient() { StartLocalMultiplayerClient(() => _networkManager.StartClient()); } public void StartClient(MatchInfo info) { StartLocalMultiplayerClient(() => _networkManager.StartClient(info)); } public void StartClient(MatchInfo info, ConnectionConfig config) { StartLocalMultiplayerClient(() => _networkManager.StartClient(info, config)); } public void StartServer() { StartLocalMultiplayerHost(() => _networkManager.StartServer()); } public void StartServer(MatchInfo info) { StartLocalMultiplayerHost(() => _networkManager.StartServer(info)); } public void StartServer(ConnectionConfig config, int maxConnections) { StartLocalMultiplayerHost(() => _networkManager.StartServer(config, maxConnections)); } public void StartHost() { StartLocalMultiplayerHost(() => _networkManager.StartHost()); } public void StartHost(MatchInfo info) { StartLocalMultiplayerHost(() => _networkManager.StartHost(info)); } public void StartHost(ConnectionConfig config, int maxConnections) { StartLocalMultiplayerHost(() => _networkManager.StartHost(config, maxConnections)); } #endregion #region Events #region Session private void OnSessionPeerStateChanged(PeerId peerId, PeerState newPeerState) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnSessionPeerStateChanged, peer: \"{0}\", state: {1}", peerId, newPeerState); } if (_desiredMode == MultiplayerMode.Client) { if (newPeerState == PeerState.Connected && _serverPeerId == null) { _serverPeerId = peerId; AppleLocalMultiplayer.PeerDiscovery.CloseBrowser(); if (_clientAction != null) { _clientAction(); _clientAction = null; } } if (newPeerState == PeerState.NotConnected && _serverPeerId == peerId) { StopAll(); } } } private void OnSessionStarted() { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnSessionStarted"); } } private void OnSessionStopped() { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnSessionStopped"); } } #endregion #region CustomPeerDiscovery private void OnCustomPeerDiscoveryPeerFound(PeerId peerId, IDictionary<string, string> peerDiscoveryInfo) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnCustomPeerDiscoveryPeerFound, peer: \"{0}\", discovery info: \n{1}", peerId, FormatDiscoveryInfo(peerDiscoveryInfo)); } } private void OnCustomPeerDiscoveryPeerLost(PeerId peerId) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnCustomPeerDiscoveryPeerLost, peer: \"{0}\"", peerId); } } private void OnCustomPeerDiscoveryStartFailed(string error) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnCustomPeerDiscoveryStartFailed, error: \"{0}\"", error); } } #endregion #region PeerDiscovery private void OnPeerDiscoveryNearbyPeerPresenting(PeerId peerId, IDictionary<string, string> peerDiscoveryInfo, ref bool shouldPresent) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnPeerDiscoveryNearbyPeerPresenting, peer: \"{0}\", discovery info: \r\n{1}", peerId, FormatDiscoveryInfo(peerDiscoveryInfo)); } } private void OnPeerDiscoveryCancelled() { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnPeerDiscoveryCancelled"); } StopAll(); } private void OnPeerDiscoveryFinished() { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnPeerDiscoveryFinished"); } } #endregion #region CustomServiceAdvertiser private void OnCustomServiceAdvertiserInvitationReceived(PeerId invitingPeerId, AppleLocalMultiplayer.InvitationHandler invitationHandler) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnCustomServiceAdvertiserInvitationReceived, inviting peer: \"{0}\"", invitingPeerId); } } private void OnCustomServiceAdvertiserStartFailed(string error) { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnCustomServiceAdvertiserStartFailed, error: \"{0}\"", error); } } #endregion #region ServiceAdvertiser private void OnServiceAdvertiserInvitationDismissed() { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnServiceAdvertiserInvitationDismissed"); } } private void OnServiceAdvertiserInvitationPresenting() { if (_multipeerConnectivitySettings.LogEvents) { Debug.LogFormat("Event - OnServiceAdvertiserInvitationPresenting"); } } #endregion #endregion #endif private static string FormatDiscoveryInfo(IDictionary<string, string> discoveryInfo) { if (discoveryInfo == null) return "none"; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, string> pair in discoveryInfo) { sb.AppendFormat("key: \"{0}\", value: \"{1}\"\n", pair.Key, pair.Value); } return sb.ToString(); } #if UNITY_EDITOR protected virtual void Reset() { OnValidate(); } protected virtual void OnValidate() { #if UNITY_IOS || UNITY_TVOS || UNITY_STANDALONE_OSX _multipeerConnectivitySettings.ServiceType = AppleLocalMultiplayer.Utility.StringToValidServiceTypeName(_multipeerConnectivitySettings.ServiceType); #endif } #endif [Serializable] public class LocalMultiplayerNetworkManagerSettings { [Tooltip("Indicates whether Local Multiplayer events should be logged.")] [SerializeField] private bool _logEvents; [Tooltip( "Text identifier of the service. Effectively, the name of the \"room\". " + "Must be the same for all peers who want to join the session.\n" + "Can be up to 15 characters long, valid characters include ASCII lowercase letters, numbers, and the hyphen.")] [SerializeField] private string _serviceType = "mygame"; public string ServiceType { get { return _serviceType; } set { if (value == null) throw new ArgumentNullException("value"); #if UNITY_IOS || UNITY_TVOS || UNITY_STANDALONE_OSX _serviceType = AppleLocalMultiplayer.Utility.StringToValidServiceTypeName(value); #else _serviceType = value; #endif } } public bool LogEvents { get { return _logEvents; } set { _logEvents = value; } } } private enum MultiplayerMode { None, Host, Client } }
[ "[", "RequireComponent", "(", "typeof", "(", "NetworkManager", ")", ")", "]", "public", "class", "AppleLocalMultiplayerNetworkManagerHelper", ":", "MonoBehaviour", "{", "[", "SerializeField", "]", "protected", "LocalMultiplayerNetworkManagerSettings", "_multipeerConnectivitySettings", "=", "new", "LocalMultiplayerNetworkManagerSettings", "(", ")", ";", "[", "SerializeField", "]", "[", "HideInInspector", "]", "protected", "NetworkManager", "_networkManager", ";", "if", "UNITY_IOS", "||", "UNITY_TVOS", "||", "UNITY_STANDALONE_OSX", "private", "MultiplayerMode", "_desiredMode", "=", "MultiplayerMode", ".", "None", ";", "private", "Action", "_clientAction", ";", "private", "Action", "_hostAction", ";", "private", "PeerId", "_serverPeerId", ";", "private", "ICustomDeviceBrowser", "_customDeviceBrowser", ";", "public", "bool", "IsInitialized", "{", "get", ";", "private", "set", ";", "}", "public", "IDictionary", "<", "string", ",", "string", ">", "DiscoveryInfo", "{", "get", ";", "set", ";", "}", "private", "void", "OnEnable", "(", ")", "{", "_networkManager", "=", "GetComponent", "<", "NetworkManager", ">", "(", ")", ";", "try", "{", "AppleLocalMultiplayer", ".", "Session", ".", "SetServiceType", "(", "_multipeerConnectivitySettings", ".", "ServiceType", ")", ";", "IsInitialized", "=", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Debug", ".", "LogException", "(", "e", ")", ";", "}", "AppleLocalMultiplayer", ".", "Session", ".", "PeerStateChanged", "+=", "OnSessionPeerStateChanged", ";", "AppleLocalMultiplayer", ".", "Session", ".", "Started", "+=", "OnSessionStarted", ";", "AppleLocalMultiplayer", ".", "Session", ".", "Stopped", "+=", "OnSessionStopped", ";", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "PeerFound", "+=", "OnCustomPeerDiscoveryPeerFound", ";", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "PeerLost", "+=", "OnCustomPeerDiscoveryPeerLost", ";", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "StartFailed", "+=", "OnCustomPeerDiscoveryStartFailed", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "NearbyPeerPresenting", "+=", "OnPeerDiscoveryNearbyPeerPresenting", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "Cancelled", "+=", "OnPeerDiscoveryCancelled", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "Finished", "+=", "OnPeerDiscoveryFinished", ";", "AppleLocalMultiplayer", ".", "CustomServiceAdvertiser", ".", "InvitationReceived", "+=", "OnCustomServiceAdvertiserInvitationReceived", ";", "AppleLocalMultiplayer", ".", "CustomServiceAdvertiser", ".", "StartFailed", "+=", "OnCustomServiceAdvertiserStartFailed", ";", "AppleLocalMultiplayer", ".", "ServiceAdvertiser", ".", "InvitationDismissed", "+=", "OnServiceAdvertiserInvitationDismissed", ";", "AppleLocalMultiplayer", ".", "ServiceAdvertiser", ".", "InvitationPresenting", "+=", "OnServiceAdvertiserInvitationPresenting", ";", "}", "private", "void", "OnDisable", "(", ")", "{", "AppleLocalMultiplayer", ".", "Session", ".", "PeerStateChanged", "-=", "OnSessionPeerStateChanged", ";", "AppleLocalMultiplayer", ".", "Session", ".", "Started", "-=", "OnSessionStarted", ";", "AppleLocalMultiplayer", ".", "Session", ".", "Stopped", "-=", "OnSessionStopped", ";", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "PeerFound", "-=", "OnCustomPeerDiscoveryPeerFound", ";", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "PeerLost", "-=", "OnCustomPeerDiscoveryPeerLost", ";", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "StartFailed", "-=", "OnCustomPeerDiscoveryStartFailed", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "NearbyPeerPresenting", "-=", "OnPeerDiscoveryNearbyPeerPresenting", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "Cancelled", "-=", "OnPeerDiscoveryCancelled", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "Finished", "-=", "OnPeerDiscoveryFinished", ";", "AppleLocalMultiplayer", ".", "CustomServiceAdvertiser", ".", "InvitationReceived", "-=", "OnCustomServiceAdvertiserInvitationReceived", ";", "AppleLocalMultiplayer", ".", "CustomServiceAdvertiser", ".", "StartFailed", "-=", "OnCustomServiceAdvertiserStartFailed", ";", "AppleLocalMultiplayer", ".", "ServiceAdvertiser", ".", "InvitationDismissed", "-=", "OnServiceAdvertiserInvitationDismissed", ";", "AppleLocalMultiplayer", ".", "ServiceAdvertiser", ".", "InvitationPresenting", "-=", "OnServiceAdvertiserInvitationPresenting", ";", "}", "public", "void", "SetCustomDeviceBrowser", "(", "ICustomDeviceBrowser", "customDeviceBrowser", ")", "{", "if", "(", "_customDeviceBrowser", "!=", "null", ")", "{", "_customDeviceBrowser", ".", "OnPeerPicked", "-=", "OnPeerPicked", ";", "}", "_customDeviceBrowser", "=", "customDeviceBrowser", ";", "if", "(", "_customDeviceBrowser", "!=", "null", ")", "{", "_customDeviceBrowser", ".", "OnPeerPicked", "+=", "OnPeerPicked", ";", "}", "}", "private", "void", "StartLocalMultiplayerClient", "(", "Action", "onReadyAction", ")", "{", "_clientAction", "=", "onReadyAction", ";", "_serverPeerId", "=", "null", ";", "_desiredMode", "=", "MultiplayerMode", ".", "Client", ";", "StartSession", "(", ")", ";", "if", "(", "_customDeviceBrowser", "!=", "null", ")", "{", "_customDeviceBrowser", ".", "Open", "(", ")", ";", "}", "else", "{", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "OpenBrowser", "(", ")", ";", "}", "}", "private", "void", "StartLocalMultiplayerHost", "(", "Action", "onReadyAction", ")", "{", "_hostAction", "=", "onReadyAction", ";", "_desiredMode", "=", "MultiplayerMode", ".", "Host", ";", "StartSession", "(", ")", ";", "AppleLocalMultiplayer", ".", "ServiceAdvertiser", ".", "StartAdvertising", "(", "DiscoveryInfo", ")", ";", "if", "(", "_hostAction", "!=", "null", ")", "{", "_hostAction", "(", ")", ";", "_hostAction", "=", "null", ";", "}", "}", "private", "void", "StopAll", "(", ")", "{", "AppleLocalMultiplayer", ".", "ServiceAdvertiser", ".", "StopAdvertising", "(", ")", ";", "_networkManager", ".", "StopHost", "(", ")", ";", "_serverPeerId", "=", "null", ";", "_desiredMode", "=", "MultiplayerMode", ".", "None", ";", "}", "private", "void", "StartSession", "(", ")", "{", "AppleLocalMultiplayer", ".", "Session", ".", "SetServerPort", "(", "_networkManager", ".", "networkPort", ")", ";", "AppleLocalMultiplayer", ".", "Session", ".", "StartSession", "(", ")", ";", "}", "private", "void", "OnPeerPicked", "(", "PeerId", "peerId", ")", "{", "AppleLocalMultiplayer", ".", "CustomPeerDiscovery", ".", "InvitePeer", "(", "peerId", ")", ";", "if", "(", "_customDeviceBrowser", "!=", "null", ")", "{", "_customDeviceBrowser", ".", "Close", "(", ")", ";", "}", "}", "region", " NetworkManager methods", "public", "void", "StartClient", "(", ")", "{", "StartLocalMultiplayerClient", "(", "(", ")", "=>", "_networkManager", ".", "StartClient", "(", ")", ")", ";", "}", "public", "void", "StartClient", "(", "MatchInfo", "info", ")", "{", "StartLocalMultiplayerClient", "(", "(", ")", "=>", "_networkManager", ".", "StartClient", "(", "info", ")", ")", ";", "}", "public", "void", "StartClient", "(", "MatchInfo", "info", ",", "ConnectionConfig", "config", ")", "{", "StartLocalMultiplayerClient", "(", "(", ")", "=>", "_networkManager", ".", "StartClient", "(", "info", ",", "config", ")", ")", ";", "}", "public", "void", "StartServer", "(", ")", "{", "StartLocalMultiplayerHost", "(", "(", ")", "=>", "_networkManager", ".", "StartServer", "(", ")", ")", ";", "}", "public", "void", "StartServer", "(", "MatchInfo", "info", ")", "{", "StartLocalMultiplayerHost", "(", "(", ")", "=>", "_networkManager", ".", "StartServer", "(", "info", ")", ")", ";", "}", "public", "void", "StartServer", "(", "ConnectionConfig", "config", ",", "int", "maxConnections", ")", "{", "StartLocalMultiplayerHost", "(", "(", ")", "=>", "_networkManager", ".", "StartServer", "(", "config", ",", "maxConnections", ")", ")", ";", "}", "public", "void", "StartHost", "(", ")", "{", "StartLocalMultiplayerHost", "(", "(", ")", "=>", "_networkManager", ".", "StartHost", "(", ")", ")", ";", "}", "public", "void", "StartHost", "(", "MatchInfo", "info", ")", "{", "StartLocalMultiplayerHost", "(", "(", ")", "=>", "_networkManager", ".", "StartHost", "(", "info", ")", ")", ";", "}", "public", "void", "StartHost", "(", "ConnectionConfig", "config", ",", "int", "maxConnections", ")", "{", "StartLocalMultiplayerHost", "(", "(", ")", "=>", "_networkManager", ".", "StartHost", "(", "config", ",", "maxConnections", ")", ")", ";", "}", "endregion", "region", " Events", "region", " Session", "private", "void", "OnSessionPeerStateChanged", "(", "PeerId", "peerId", ",", "PeerState", "newPeerState", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnSessionPeerStateChanged, peer: ", "\\\"", "{0}", "\\\"", ", state: {1}", "\"", ",", "peerId", ",", "newPeerState", ")", ";", "}", "if", "(", "_desiredMode", "==", "MultiplayerMode", ".", "Client", ")", "{", "if", "(", "newPeerState", "==", "PeerState", ".", "Connected", "&&", "_serverPeerId", "==", "null", ")", "{", "_serverPeerId", "=", "peerId", ";", "AppleLocalMultiplayer", ".", "PeerDiscovery", ".", "CloseBrowser", "(", ")", ";", "if", "(", "_clientAction", "!=", "null", ")", "{", "_clientAction", "(", ")", ";", "_clientAction", "=", "null", ";", "}", "}", "if", "(", "newPeerState", "==", "PeerState", ".", "NotConnected", "&&", "_serverPeerId", "==", "peerId", ")", "{", "StopAll", "(", ")", ";", "}", "}", "}", "private", "void", "OnSessionStarted", "(", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnSessionStarted", "\"", ")", ";", "}", "}", "private", "void", "OnSessionStopped", "(", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnSessionStopped", "\"", ")", ";", "}", "}", "endregion", "region", " CustomPeerDiscovery", "private", "void", "OnCustomPeerDiscoveryPeerFound", "(", "PeerId", "peerId", ",", "IDictionary", "<", "string", ",", "string", ">", "peerDiscoveryInfo", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnCustomPeerDiscoveryPeerFound, peer: ", "\\\"", "{0}", "\\\"", ", discovery info: ", "\\n", "{1}", "\"", ",", "peerId", ",", "FormatDiscoveryInfo", "(", "peerDiscoveryInfo", ")", ")", ";", "}", "}", "private", "void", "OnCustomPeerDiscoveryPeerLost", "(", "PeerId", "peerId", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnCustomPeerDiscoveryPeerLost, peer: ", "\\\"", "{0}", "\\\"", "\"", ",", "peerId", ")", ";", "}", "}", "private", "void", "OnCustomPeerDiscoveryStartFailed", "(", "string", "error", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnCustomPeerDiscoveryStartFailed, error: ", "\\\"", "{0}", "\\\"", "\"", ",", "error", ")", ";", "}", "}", "endregion", "region", " PeerDiscovery", "private", "void", "OnPeerDiscoveryNearbyPeerPresenting", "(", "PeerId", "peerId", ",", "IDictionary", "<", "string", ",", "string", ">", "peerDiscoveryInfo", ",", "ref", "bool", "shouldPresent", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnPeerDiscoveryNearbyPeerPresenting, peer: ", "\\\"", "{0}", "\\\"", ", discovery info: ", "\\r", "\\n", "{1}", "\"", ",", "peerId", ",", "FormatDiscoveryInfo", "(", "peerDiscoveryInfo", ")", ")", ";", "}", "}", "private", "void", "OnPeerDiscoveryCancelled", "(", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnPeerDiscoveryCancelled", "\"", ")", ";", "}", "StopAll", "(", ")", ";", "}", "private", "void", "OnPeerDiscoveryFinished", "(", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnPeerDiscoveryFinished", "\"", ")", ";", "}", "}", "endregion", "region", " CustomServiceAdvertiser", "private", "void", "OnCustomServiceAdvertiserInvitationReceived", "(", "PeerId", "invitingPeerId", ",", "AppleLocalMultiplayer", ".", "InvitationHandler", "invitationHandler", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnCustomServiceAdvertiserInvitationReceived, inviting peer: ", "\\\"", "{0}", "\\\"", "\"", ",", "invitingPeerId", ")", ";", "}", "}", "private", "void", "OnCustomServiceAdvertiserStartFailed", "(", "string", "error", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnCustomServiceAdvertiserStartFailed, error: ", "\\\"", "{0}", "\\\"", "\"", ",", "error", ")", ";", "}", "}", "endregion", "region", " ServiceAdvertiser", "private", "void", "OnServiceAdvertiserInvitationDismissed", "(", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnServiceAdvertiserInvitationDismissed", "\"", ")", ";", "}", "}", "private", "void", "OnServiceAdvertiserInvitationPresenting", "(", ")", "{", "if", "(", "_multipeerConnectivitySettings", ".", "LogEvents", ")", "{", "Debug", ".", "LogFormat", "(", "\"", "Event - OnServiceAdvertiserInvitationPresenting", "\"", ")", ";", "}", "}", "endregion", "endregion", "endif", "private", "static", "string", "FormatDiscoveryInfo", "(", "IDictionary", "<", "string", ",", "string", ">", "discoveryInfo", ")", "{", "if", "(", "discoveryInfo", "==", "null", ")", "return", "\"", "none", "\"", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "foreach", "(", "KeyValuePair", "<", "string", ",", "string", ">", "pair", "in", "discoveryInfo", ")", "{", "sb", ".", "AppendFormat", "(", "\"", "key: ", "\\\"", "{0}", "\\\"", ", value: ", "\\\"", "{1}", "\\\"", "\\n", "\"", ",", "pair", ".", "Key", ",", "pair", ".", "Value", ")", ";", "}", "return", "sb", ".", "ToString", "(", ")", ";", "}", "if", "UNITY_EDITOR", "protected", "virtual", "void", "Reset", "(", ")", "{", "OnValidate", "(", ")", ";", "}", "protected", "virtual", "void", "OnValidate", "(", ")", "{", "if", "UNITY_IOS", "||", "UNITY_TVOS", "||", "UNITY_STANDALONE_OSX", "_multipeerConnectivitySettings", ".", "ServiceType", "=", "AppleLocalMultiplayer", ".", "Utility", ".", "StringToValidServiceTypeName", "(", "_multipeerConnectivitySettings", ".", "ServiceType", ")", ";", "endif", "}", "endif", "[", "Serializable", "]", "public", "class", "LocalMultiplayerNetworkManagerSettings", "{", "[", "Tooltip", "(", "\"", "Indicates whether Local Multiplayer events should be logged.", "\"", ")", "]", "[", "SerializeField", "]", "private", "bool", "_logEvents", ";", "[", "Tooltip", "(", "\"", "Text identifier of the service. Effectively, the name of the ", "\\\"", "room", "\\\"", ". ", "\"", "+", "\"", "Must be the same for all peers who want to join the session.", "\\n", "\"", "+", "\"", "Can be up to 15 characters long, valid characters include ASCII lowercase letters, numbers, and the hyphen.", "\"", ")", "]", "[", "SerializeField", "]", "private", "string", "_serviceType", "=", "\"", "mygame", "\"", ";", "public", "string", "ServiceType", "{", "get", "{", "return", "_serviceType", ";", "}", "set", "{", "if", "(", "value", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "value", "\"", ")", ";", "if", "UNITY_IOS", "||", "UNITY_TVOS", "||", "UNITY_STANDALONE_OSX", "_serviceType", "=", "AppleLocalMultiplayer", ".", "Utility", ".", "StringToValidServiceTypeName", "(", "value", ")", ";", "else", "_serviceType", "=", "value", ";", "endif", "}", "}", "public", "bool", "LogEvents", "{", "get", "{", "return", "_logEvents", ";", "}", "set", "{", "_logEvents", "=", "value", ";", "}", "}", "}", "private", "enum", "MultiplayerMode", "{", "None", ",", "Host", ",", "Client", "}", "}" ]
A helper class that works in conjunction with .
[ "A", "helper", "class", "that", "works", "in", "conjunction", "with", "." ]
[ "/// <summary>", "/// A custom nearby peer browser can be used instead of a native one.", "/// </summary>", "/// <summary>", "/// Gets a value indicating whether the plugin has initialized successfully.", "/// </summary>", "/// <summary>", "/// Discovery info sent to other peers when advertising.", "/// </summary>", "// Setting the service type. Must be unique for every application", "// Registering the event listeners", "// Unregistering the event listeners", "/// <summary>", "/// Sets the custom nearby peer browser.", "/// </summary>", "// Trying to invite the device picked by user", "/// <seealso cref=\"NetworkManager.StartClient()\"/>", "/// <seealso cref=\"NetworkManager.StartClient()\"/>", "/// <seealso cref=\"NetworkManager.StartClient()\"/>", "/// <seealso cref=\"NetworkManager.StartServer()\"/>", "/// <seealso cref=\"NetworkManager.StartServer()\"/>", "/// <seealso cref=\"NetworkManager.StartServer()\"/>", "/// <seealso cref=\"NetworkManager.StartHost()\"/>", "/// <seealso cref=\"NetworkManager.StartHost()\"/>", "/// <seealso cref=\"NetworkManager.StartHost()\"/>", "// The first connected peer is the server", "// Stop networking if disconnected from the server", "/// <summary>", "/// Container for Local Multiplayer settings.", "/// </summary>", "/// <tocexclude />" ]
[ { "param": "MonoBehaviour", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MonoBehaviour", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "The NetworkManager.Start* family of methods is mirrored, just use this class\ninstead of using NetworkManager directly to start your client/server/host.", "docstring_tokens": [ "The", "NetworkManager", ".", "Start", "*", "family", "of", "methods", "is", "mirrored", "just", "use", "this", "class", "instead", "of", "using", "NetworkManager", "directly", "to", "start", "your", "client", "/", "server", "/", "host", "." ] } ] }
false
15
2,642
81
54792a2e7cf0d996ecd2e847ca0303ea3b13ae75
mikiec84/3dwikipedia
code/LIBS/vlfeat-0.9.16/docsrc/formatter.py
[ "MIT" ]
Python
Formatter
f = Formatter(LINES) parse the array of strings LINES. f = Formatter(LINES, FUNCS) takes the dictionary of functions FUNCS. Function names must be uppercase. The dictionary entries are used to cross link functions in the generated documentation. Formatter(LINES, FUNCS, LINKTYPE) produces links of the specified type. Use 'a' for HTML anchors and 'wiki' for MediaWiki style links. f.toDOM() process the data to construct an XML (HTML) representation of them.
f = Formatter(LINES) parse the array of strings LINES. f = Formatter(LINES, FUNCS) takes the dictionary of functions FUNCS. Function names must be uppercase. The dictionary entries are used to cross link functions in the generated documentation. Formatter(LINES, FUNCS, LINKTYPE) produces links of the specified type. Use 'a' for HTML anchors and 'wiki' for MediaWiki style links. f.toDOM() process the data to construct an XML (HTML) representation of them.
[ "f", "=", "Formatter", "(", "LINES", ")", "parse", "the", "array", "of", "strings", "LINES", ".", "f", "=", "Formatter", "(", "LINES", "FUNCS", ")", "takes", "the", "dictionary", "of", "functions", "FUNCS", ".", "Function", "names", "must", "be", "uppercase", ".", "The", "dictionary", "entries", "are", "used", "to", "cross", "link", "functions", "in", "the", "generated", "documentation", ".", "Formatter", "(", "LINES", "FUNCS", "LINKTYPE", ")", "produces", "links", "of", "the", "specified", "type", ".", "Use", "'", "a", "'", "for", "HTML", "anchors", "and", "'", "wiki", "'", "for", "MediaWiki", "style", "links", ".", "f", ".", "toDOM", "()", "process", "the", "data", "to", "construct", "an", "XML", "(", "HTML", ")", "representation", "of", "them", "." ]
class Formatter: # -------------------------------------------------------------------- """ f = Formatter(LINES) parse the array of strings LINES. f = Formatter(LINES, FUNCS) takes the dictionary of functions FUNCS. Function names must be uppercase. The dictionary entries are used to cross link functions in the generated documentation. Formatter(LINES, FUNCS, LINKTYPE) produces links of the specified type. Use 'a' for HTML anchors and 'wiki' for MediaWiki style links. f.toDOM() process the data to construct an XML (HTML) representation of them. """ def __init__ (self, lines, funcs={}, linktype='a'): self.indentinit = 0 lineone = lines[0] while lineone.startswith(' '): lineone = lineone[1:] self.indentinit += 1 self.tokens = Lexer(lines) self.xmldoc = xml.dom.minidom.Document() self.funcs = funcs self.linktype = linktype #print self.tokens def toTextNode(self,s): return self.xmldoc.createTextNode(unicode(s, 'iso-8859-1')) def addAttr(self, tag, attr, val): x = self.xmldoc.createAttribute(attr) x.nodeValue = val tag.setAttributeNode(x) def addText(self, tag, s): txt = self.toTextNode(s) tag.appendChild(txt) def addFancyText(self, tag, s): "Adds text while transforming function references to links." xs = [] iter = re.finditer('([A-Z][A-Z0-9_]*)\([^\)]*\)', s) last = -1 for i in iter: func_name = i.group(1) # lookup function name in dictionary if self.funcs.has_key(func_name.upper()): # retrieve function HTML location func_href = self.funcs[func_name.upper()] # add text so far xs.append(self.toTextNode(s[last+1:i.start()])) if self.linktype == 'a': # add link to function atag = self.xmldoc.createElement(u"a") self.addText(atag, i.group(1)) atag.setAttribute(u"href", u"%s" % (func_href)) xs.append(atag) elif self.linktype == 'wiki': linktxt = "[[%s|%s]]" % (func_href, i.group(1)) xs.append(self.toTextNode(linktxt)) # set head last = i.start()+len(i.group(1))-1 #else: # print "function: %s not found" % func_name xs.append(self.toTextNode(s[last+1:])) for x in xs: tag.appendChild(x) # ................................................................ # E, B, L, PL, BL, DL, ... def parse_Terminal(self, T): "If the next terminal on the stream is of type T, the terminal" "is extracted and returned. Otherwise the function returns None" pos = self.tokens.getpos() t = self.tokens.next() if t.isa(T): return t self.tokens.seek(pos) return None # ................................................................ # DIV(N) -> (B | P(N) | BL(N) | DL(N) | V(N))+ def parse_DIV(self, indent): "Parse a DIV(N) symbol. A DIV(N) a sequence of blank" "lines (B or other blocks at indentation level N, such as" "pharagraphs P(N), bullet lists BL(N), description lists DN(N)" pos = self.tokens.getpos() xs = [] while True: x = self.parse_Terminal(B) if x: continue x = self.parse_P(indent) if x: xs.append(x) continue x = self.parse_V(indent) if x: xs.append(x) continue x = self.parse_UL(indent) if x: xs.append(x) continue x = self.parse_DL(indent) if x: xs.append(x) continue break if len(xs) == 0: return None return xs # ................................................................ # P(N) -> PL(N) L(N)* def parse_P(self, indent): content = "\n" good = False pos = self.tokens.getpos() # Introduced by PL x = self.parse_Terminal(PL) if x: if x.indent == indent: content += x.content + "\n" good = True else: self.tokens.back() if not good: return None # Continued by zero or more L while True: x = self.parse_Terminal(L) if x: if x.indent == indent: content += x.content + "\n" good = True continue else: self.tokens.back() break ptag = self.xmldoc.createElement("p") self.addFancyText(ptag, content) return ptag # ................................................................ # V(N) -> L(M)+, M > N def parse_V(self, indent): content = "\n" good = False pos = self.tokens.getpos() while True: x = self.parse_Terminal(L) if x: if x.indent > indent: content += " "*(x.indent - indent) + x.content + "\n" good = True continue else: self.tokens.back() x = self.parse_Terminal(B) if x: content += "\n" continue break if good: ptag = self.xmldoc.createElement("pre") # remove potential blank line at the end if content[-2:] == "\n\n": content= content[:-1] self.addText(ptag, content) return ptag self.tokens.seek(pos) return None # ................................................................ # UL(N) -> ULI(N)+ def parse_UL(self, indent): xs = [] while True: x = self.parse_ULI(indent) if x: xs.append(x) continue break if len(xs) == 0: return None ultag = self.xmldoc.createElement("ul") for x in xs: ultag.appendChild(x) return ultag # ................................................................ # ULI(N) -> UL(N,M) L(M)* DIV(M), M > N def parse_ULI(self, indent): content = "\n" good = False pos = self.tokens.getpos() # Introduced by UL x = self.parse_Terminal(BL) if x: if x.indent == indent: content += x.inner_content + "\n" indent = x.inner_indent good = True else: self.tokens.back() if not good: return None # Continued by zero or more L while True: x = self.parse_Terminal(L) if x: if x.indent == indent: content += x.content + "\n" good = True continue else: self.tokens.back() break litag = self.xmldoc.createElement(u"li") ptag = self.xmldoc.createElement(u"p") self.addFancyText(ptag, content) litag.appendChild(ptag) # Continued by DIV xs = self.parse_DIV(indent) if xs: for x in xs: litag.appendChild(x) return litag # ................................................................ # DL(N) -> DI(N)+ def parse_DL(self, indent): xs = [] while True: x = self.parse_DI(indent) if x: xs += x continue break if len(xs) == 0: return None dltag = self.xmldoc.createElement(u"dl") for x in xs: dltag.appendChild(x) return dltag # ................................................................ # DI(N) -> DL(N) DIV(M)?, M > N def parse_DI(self, indent): content = "\n" good = False pos = self.tokens.getpos() xs = [] # Introduced by DL x = self.parse_Terminal(DL) if x: if x.indent == indent: content += x.content + "\n" good = True else: self.tokens.back() if not good: return None if False: # adds text after :: as part of the description dd dttag = self.xmldoc.createElement(u"dt") dttxt = self.toTextNode(content) dttag.appendChild(dttxt) xs.append(dttag) # Inject inner_content c = x.inner_content.strip() if len(c) > 0: tk = PL() tk.content = x.inner_content t = self.tokens.next() self.tokens.back() if t.isa(L) and t.indent > indent: tk.indent = t.indent else: tk.indent = indent+1 ; self.tokens.rewrite(tk) self.tokens.back() else: # adds text after :: as part of the description term dt dttag = self.xmldoc.createElement(u"dt") dttxt = self.toTextNode(content) dttag.appendChild(dttxt) c = x.inner_content.strip() if len(c) > 0: deftag = self.xmldoc.createElement(u"span") self.addAttr(deftag, "class", "defaults") self.addText(deftag, c) dttag.appendChild(deftag) xs.append(dttag) # Continued by DIV t = self.tokens.next() self.tokens.back() if t.isa(L) and t.indent > indent: xs_ = self.parse_DIV(t.indent) if len(xs_) > 0: ddtag = self.xmldoc.createElement(u"dd") for x in xs_: ddtag.appendChild(x) xs.append(ddtag) return xs # ................................................................ def toDOM(self): # write <mfile></mfile> xmf = self.xmldoc.createElement("div") xmf.setAttribute(u"class", u"documentation") self.xmldoc.appendChild(xmf) # parse documentation xs = self.parse_DIV(self.indentinit) for x in xs: xmf.appendChild(x) return self.xmldoc
[ "class", "Formatter", ":", "def", "__init__", "(", "self", ",", "lines", ",", "funcs", "=", "{", "}", ",", "linktype", "=", "'a'", ")", ":", "self", ".", "indentinit", "=", "0", "lineone", "=", "lines", "[", "0", "]", "while", "lineone", ".", "startswith", "(", "' '", ")", ":", "lineone", "=", "lineone", "[", "1", ":", "]", "self", ".", "indentinit", "+=", "1", "self", ".", "tokens", "=", "Lexer", "(", "lines", ")", "self", ".", "xmldoc", "=", "xml", ".", "dom", ".", "minidom", ".", "Document", "(", ")", "self", ".", "funcs", "=", "funcs", "self", ".", "linktype", "=", "linktype", "def", "toTextNode", "(", "self", ",", "s", ")", ":", "return", "self", ".", "xmldoc", ".", "createTextNode", "(", "unicode", "(", "s", ",", "'iso-8859-1'", ")", ")", "def", "addAttr", "(", "self", ",", "tag", ",", "attr", ",", "val", ")", ":", "x", "=", "self", ".", "xmldoc", ".", "createAttribute", "(", "attr", ")", "x", ".", "nodeValue", "=", "val", "tag", ".", "setAttributeNode", "(", "x", ")", "def", "addText", "(", "self", ",", "tag", ",", "s", ")", ":", "txt", "=", "self", ".", "toTextNode", "(", "s", ")", "tag", ".", "appendChild", "(", "txt", ")", "def", "addFancyText", "(", "self", ",", "tag", ",", "s", ")", ":", "\"Adds text while transforming function references to links.\"", "xs", "=", "[", "]", "iter", "=", "re", ".", "finditer", "(", "'([A-Z][A-Z0-9_]*)\\([^\\)]*\\)'", ",", "s", ")", "last", "=", "-", "1", "for", "i", "in", "iter", ":", "func_name", "=", "i", ".", "group", "(", "1", ")", "if", "self", ".", "funcs", ".", "has_key", "(", "func_name", ".", "upper", "(", ")", ")", ":", "func_href", "=", "self", ".", "funcs", "[", "func_name", ".", "upper", "(", ")", "]", "xs", ".", "append", "(", "self", ".", "toTextNode", "(", "s", "[", "last", "+", "1", ":", "i", ".", "start", "(", ")", "]", ")", ")", "if", "self", ".", "linktype", "==", "'a'", ":", "atag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"a\"", ")", "self", ".", "addText", "(", "atag", ",", "i", ".", "group", "(", "1", ")", ")", "atag", ".", "setAttribute", "(", "u\"href\"", ",", "u\"%s\"", "%", "(", "func_href", ")", ")", "xs", ".", "append", "(", "atag", ")", "elif", "self", ".", "linktype", "==", "'wiki'", ":", "linktxt", "=", "\"[[%s|%s]]\"", "%", "(", "func_href", ",", "i", ".", "group", "(", "1", ")", ")", "xs", ".", "append", "(", "self", ".", "toTextNode", "(", "linktxt", ")", ")", "last", "=", "i", ".", "start", "(", ")", "+", "len", "(", "i", ".", "group", "(", "1", ")", ")", "-", "1", "xs", ".", "append", "(", "self", ".", "toTextNode", "(", "s", "[", "last", "+", "1", ":", "]", ")", ")", "for", "x", "in", "xs", ":", "tag", ".", "appendChild", "(", "x", ")", "def", "parse_Terminal", "(", "self", ",", "T", ")", ":", "\"If the next terminal on the stream is of type T, the terminal\"", "\"is extracted and returned. Otherwise the function returns None\"", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "t", "=", "self", ".", "tokens", ".", "next", "(", ")", "if", "t", ".", "isa", "(", "T", ")", ":", "return", "t", "self", ".", "tokens", ".", "seek", "(", "pos", ")", "return", "None", "def", "parse_DIV", "(", "self", ",", "indent", ")", ":", "\"Parse a DIV(N) symbol. A DIV(N) a sequence of blank\"", "\"lines (B or other blocks at indentation level N, such as\"", "\"pharagraphs P(N), bullet lists BL(N), description lists DN(N)\"", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "xs", "=", "[", "]", "while", "True", ":", "x", "=", "self", ".", "parse_Terminal", "(", "B", ")", "if", "x", ":", "continue", "x", "=", "self", ".", "parse_P", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "x", "=", "self", ".", "parse_V", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "x", "=", "self", ".", "parse_UL", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "x", "=", "self", ".", "parse_DL", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "break", "if", "len", "(", "xs", ")", "==", "0", ":", "return", "None", "return", "xs", "def", "parse_P", "(", "self", ",", "indent", ")", ":", "content", "=", "\"\\n\"", "good", "=", "False", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "x", "=", "self", ".", "parse_Terminal", "(", "PL", ")", "if", "x", ":", "if", "x", ".", "indent", "==", "indent", ":", "content", "+=", "x", ".", "content", "+", "\"\\n\"", "good", "=", "True", "else", ":", "self", ".", "tokens", ".", "back", "(", ")", "if", "not", "good", ":", "return", "None", "while", "True", ":", "x", "=", "self", ".", "parse_Terminal", "(", "L", ")", "if", "x", ":", "if", "x", ".", "indent", "==", "indent", ":", "content", "+=", "x", ".", "content", "+", "\"\\n\"", "good", "=", "True", "continue", "else", ":", "self", ".", "tokens", ".", "back", "(", ")", "break", "ptag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "\"p\"", ")", "self", ".", "addFancyText", "(", "ptag", ",", "content", ")", "return", "ptag", "def", "parse_V", "(", "self", ",", "indent", ")", ":", "content", "=", "\"\\n\"", "good", "=", "False", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "while", "True", ":", "x", "=", "self", ".", "parse_Terminal", "(", "L", ")", "if", "x", ":", "if", "x", ".", "indent", ">", "indent", ":", "content", "+=", "\" \"", "*", "(", "x", ".", "indent", "-", "indent", ")", "+", "x", ".", "content", "+", "\"\\n\"", "good", "=", "True", "continue", "else", ":", "self", ".", "tokens", ".", "back", "(", ")", "x", "=", "self", ".", "parse_Terminal", "(", "B", ")", "if", "x", ":", "content", "+=", "\"\\n\"", "continue", "break", "if", "good", ":", "ptag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "\"pre\"", ")", "if", "content", "[", "-", "2", ":", "]", "==", "\"\\n\\n\"", ":", "content", "=", "content", "[", ":", "-", "1", "]", "self", ".", "addText", "(", "ptag", ",", "content", ")", "return", "ptag", "self", ".", "tokens", ".", "seek", "(", "pos", ")", "return", "None", "def", "parse_UL", "(", "self", ",", "indent", ")", ":", "xs", "=", "[", "]", "while", "True", ":", "x", "=", "self", ".", "parse_ULI", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "break", "if", "len", "(", "xs", ")", "==", "0", ":", "return", "None", "ultag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "\"ul\"", ")", "for", "x", "in", "xs", ":", "ultag", ".", "appendChild", "(", "x", ")", "return", "ultag", "def", "parse_ULI", "(", "self", ",", "indent", ")", ":", "content", "=", "\"\\n\"", "good", "=", "False", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "x", "=", "self", ".", "parse_Terminal", "(", "BL", ")", "if", "x", ":", "if", "x", ".", "indent", "==", "indent", ":", "content", "+=", "x", ".", "inner_content", "+", "\"\\n\"", "indent", "=", "x", ".", "inner_indent", "good", "=", "True", "else", ":", "self", ".", "tokens", ".", "back", "(", ")", "if", "not", "good", ":", "return", "None", "while", "True", ":", "x", "=", "self", ".", "parse_Terminal", "(", "L", ")", "if", "x", ":", "if", "x", ".", "indent", "==", "indent", ":", "content", "+=", "x", ".", "content", "+", "\"\\n\"", "good", "=", "True", "continue", "else", ":", "self", ".", "tokens", ".", "back", "(", ")", "break", "litag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"li\"", ")", "ptag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"p\"", ")", "self", ".", "addFancyText", "(", "ptag", ",", "content", ")", "litag", ".", "appendChild", "(", "ptag", ")", "xs", "=", "self", ".", "parse_DIV", "(", "indent", ")", "if", "xs", ":", "for", "x", "in", "xs", ":", "litag", ".", "appendChild", "(", "x", ")", "return", "litag", "def", "parse_DL", "(", "self", ",", "indent", ")", ":", "xs", "=", "[", "]", "while", "True", ":", "x", "=", "self", ".", "parse_DI", "(", "indent", ")", "if", "x", ":", "xs", "+=", "x", "continue", "break", "if", "len", "(", "xs", ")", "==", "0", ":", "return", "None", "dltag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"dl\"", ")", "for", "x", "in", "xs", ":", "dltag", ".", "appendChild", "(", "x", ")", "return", "dltag", "def", "parse_DI", "(", "self", ",", "indent", ")", ":", "content", "=", "\"\\n\"", "good", "=", "False", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "xs", "=", "[", "]", "x", "=", "self", ".", "parse_Terminal", "(", "DL", ")", "if", "x", ":", "if", "x", ".", "indent", "==", "indent", ":", "content", "+=", "x", ".", "content", "+", "\"\\n\"", "good", "=", "True", "else", ":", "self", ".", "tokens", ".", "back", "(", ")", "if", "not", "good", ":", "return", "None", "if", "False", ":", "dttag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"dt\"", ")", "dttxt", "=", "self", ".", "toTextNode", "(", "content", ")", "dttag", ".", "appendChild", "(", "dttxt", ")", "xs", ".", "append", "(", "dttag", ")", "c", "=", "x", ".", "inner_content", ".", "strip", "(", ")", "if", "len", "(", "c", ")", ">", "0", ":", "tk", "=", "PL", "(", ")", "tk", ".", "content", "=", "x", ".", "inner_content", "t", "=", "self", ".", "tokens", ".", "next", "(", ")", "self", ".", "tokens", ".", "back", "(", ")", "if", "t", ".", "isa", "(", "L", ")", "and", "t", ".", "indent", ">", "indent", ":", "tk", ".", "indent", "=", "t", ".", "indent", "else", ":", "tk", ".", "indent", "=", "indent", "+", "1", ";", "self", ".", "tokens", ".", "rewrite", "(", "tk", ")", "self", ".", "tokens", ".", "back", "(", ")", "else", ":", "dttag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"dt\"", ")", "dttxt", "=", "self", ".", "toTextNode", "(", "content", ")", "dttag", ".", "appendChild", "(", "dttxt", ")", "c", "=", "x", ".", "inner_content", ".", "strip", "(", ")", "if", "len", "(", "c", ")", ">", "0", ":", "deftag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"span\"", ")", "self", ".", "addAttr", "(", "deftag", ",", "\"class\"", ",", "\"defaults\"", ")", "self", ".", "addText", "(", "deftag", ",", "c", ")", "dttag", ".", "appendChild", "(", "deftag", ")", "xs", ".", "append", "(", "dttag", ")", "t", "=", "self", ".", "tokens", ".", "next", "(", ")", "self", ".", "tokens", ".", "back", "(", ")", "if", "t", ".", "isa", "(", "L", ")", "and", "t", ".", "indent", ">", "indent", ":", "xs_", "=", "self", ".", "parse_DIV", "(", "t", ".", "indent", ")", "if", "len", "(", "xs_", ")", ">", "0", ":", "ddtag", "=", "self", ".", "xmldoc", ".", "createElement", "(", "u\"dd\"", ")", "for", "x", "in", "xs_", ":", "ddtag", ".", "appendChild", "(", "x", ")", "xs", ".", "append", "(", "ddtag", ")", "return", "xs", "def", "toDOM", "(", "self", ")", ":", "xmf", "=", "self", ".", "xmldoc", ".", "createElement", "(", "\"div\"", ")", "xmf", ".", "setAttribute", "(", "u\"class\"", ",", "u\"documentation\"", ")", "self", ".", "xmldoc", ".", "appendChild", "(", "xmf", ")", "xs", "=", "self", ".", "parse_DIV", "(", "self", ".", "indentinit", ")", "for", "x", "in", "xs", ":", "xmf", ".", "appendChild", "(", "x", ")", "return", "self", ".", "xmldoc" ]
f = Formatter(LINES) parse the array of strings LINES.
[ "f", "=", "Formatter", "(", "LINES", ")", "parse", "the", "array", "of", "strings", "LINES", "." ]
[ "# --------------------------------------------------------------------", "\"\"\"\n f = Formatter(LINES) parse the array of strings LINES.\n\n f = Formatter(LINES, FUNCS) takes the dictionary of functions\n FUNCS. Function names must be uppercase. The dictionary entries\n are used to cross link functions in the generated documentation.\n\n Formatter(LINES, FUNCS, LINKTYPE) produces links of the specified\n type. Use 'a' for HTML anchors and 'wiki' for MediaWiki style\n links.\n\n f.toDOM() process the data to construct an XML (HTML) representation\n of them.\n \"\"\"", "#print self.tokens", "\"Adds text while transforming function references to links.\"", "# lookup function name in dictionary", "# retrieve function HTML location", "# add text so far", "# add link to function", "# set head", "#else:", "# print \"function: %s not found\" % func_name", "# ................................................................", "# E, B, L, PL, BL, DL, ...", "\"If the next terminal on the stream is of type T, the terminal\"", "\"is extracted and returned. Otherwise the function returns None\"", "# ................................................................", "# DIV(N) -> (B | P(N) | BL(N) | DL(N) | V(N))+", "\"Parse a DIV(N) symbol. A DIV(N) a sequence of blank\"", "\"lines (B or other blocks at indentation level N, such as\"", "\"pharagraphs P(N), bullet lists BL(N), description lists DN(N)\"", "# ................................................................", "# P(N) -> PL(N) L(N)*", "# Introduced by PL", "# Continued by zero or more L", "# ................................................................", "# V(N) -> L(M)+, M > N", "# remove potential blank line at the end", "# ................................................................", "# UL(N) -> ULI(N)+", "# ................................................................", "# ULI(N) -> UL(N,M) L(M)* DIV(M), M > N", "# Introduced by UL", "# Continued by zero or more L", "# Continued by DIV", "# ................................................................", "# DL(N) -> DI(N)+", "# ................................................................", "# DI(N) -> DL(N) DIV(M)?, M > N", "# Introduced by DL", "# adds text after :: as part of the description dd", "# Inject inner_content", "# adds text after :: as part of the description term dt", "# Continued by DIV", "# ................................................................", "# write <mfile></mfile>", "# parse documentation" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
2,332
120
8b41f6c09e1559adb48ca222975ba46d59b49a30
baidu/Quanlse
Quanlse/QOperator.py
[ "Apache-2.0" ]
Python
QOperator
In Quanlse, operators are stored in QOperator objects, which keep track of the operator's purpose, matrix form, coefficients and the qubits it corresponds to. :param name: a user-given name :param matrix: corresponding matrix of the operator :param onSubSys: subsystem number :param coef: corresponding coefficient
In Quanlse, operators are stored in QOperator objects, which keep track of the operator's purpose, matrix form, coefficients and the qubits it corresponds to.
[ "In", "Quanlse", "operators", "are", "stored", "in", "QOperator", "objects", "which", "keep", "track", "of", "the", "operator", "'", "s", "purpose", "matrix", "form", "coefficients", "and", "the", "qubits", "it", "corresponds", "to", "." ]
class QOperator: """ In Quanlse, operators are stored in QOperator objects, which keep track of the operator's purpose, matrix form, coefficients and the qubits it corresponds to. :param name: a user-given name :param matrix: corresponding matrix of the operator :param onSubSys: subsystem number :param coef: corresponding coefficient """ def __init__(self, name: str, matrix: ndarray = None, onSubSys: int = None, coef: Union[float, complex] = 1.0) -> None: """ The constructor of the QOperator class. """ self.name = name # type: str self.matrix = matrix # type: ndarray self.onSubSys = onSubSys # type: int self.coef = coef # type: float @property def matrix(self): """ Return the corresponding matrix (type: ndarray) """ return self._matrix @matrix.setter def matrix(self, matrix: ndarray = None): """ Setter function for the matrix :param matrix: the matrix to be set to """ if matrix is not None and not isinstance(matrix, ndarray): raise Error.ArgumentError("matrix must be a numpy.ndarray!") self._matrix = matrix @property def name(self): """ Return the corresponding name of the operator. """ return self._name @name.setter def name(self, name: str): """ Modify the name of the operator. :param name: name to be changed to """ if not isinstance(name, str): raise Error.ArgumentError("name must be a str!") self._name = name @property def onSubSys(self): """ Return the corresponding subsystem number of the operator. """ return self._onSubSys @onSubSys.setter def onSubSys(self, onSubSys: int): """ Modify the corresponding subsystem of the operator. :param onSubSys: subsystem to be changed to """ if onSubSys is None: self._onSubSys = None else: if not isinstance(onSubSys, int): raise Error.ArgumentError(f"onSubSys must be an integer, instead of {type(onSubSys)}!") self._onSubSys = onSubSys @property def coef(self): """ Coefficient of the operator """ return self._coef @coef.setter def coef(self, coef: Union[float, complex] = 1.0): """ Setter for the coefficient :param: coefficient to be set to """ if coef is None: self._coef = 1.0 else: if not (isinstance(coef, float) or isinstance(coef, complex)): raise Error.ArgumentError(f"coef must be a float or complex, instead of {type(coef)}!") self._coef = coef def dump(self) -> str: """ Return base64 encoded string. :return: a base64 encoded string """ # Dump the object byteStr = pickle.dumps(self) base64str = base64.b64encode(byteStr) return base64str.decode() @staticmethod def load(base64Str: str) -> 'QOperator': """ Create object from base64 encoded string. :return: a QOperator object """ byteStr = base64.b64decode(base64Str.encode()) obj = pickle.loads(byteStr) # type: QOperator return obj
[ "class", "QOperator", ":", "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "matrix", ":", "ndarray", "=", "None", ",", "onSubSys", ":", "int", "=", "None", ",", "coef", ":", "Union", "[", "float", ",", "complex", "]", "=", "1.0", ")", "->", "None", ":", "\"\"\"\n The constructor of the QOperator class.\n \"\"\"", "self", ".", "name", "=", "name", "self", ".", "matrix", "=", "matrix", "self", ".", "onSubSys", "=", "onSubSys", "self", ".", "coef", "=", "coef", "@", "property", "def", "matrix", "(", "self", ")", ":", "\"\"\"\n Return the corresponding matrix (type: ndarray)\n \"\"\"", "return", "self", ".", "_matrix", "@", "matrix", ".", "setter", "def", "matrix", "(", "self", ",", "matrix", ":", "ndarray", "=", "None", ")", ":", "\"\"\"\n Setter function for the matrix\n\n :param matrix: the matrix to be set to\n \"\"\"", "if", "matrix", "is", "not", "None", "and", "not", "isinstance", "(", "matrix", ",", "ndarray", ")", ":", "raise", "Error", ".", "ArgumentError", "(", "\"matrix must be a numpy.ndarray!\"", ")", "self", ".", "_matrix", "=", "matrix", "@", "property", "def", "name", "(", "self", ")", ":", "\"\"\"\n Return the corresponding name of the operator.\n \"\"\"", "return", "self", ".", "_name", "@", "name", ".", "setter", "def", "name", "(", "self", ",", "name", ":", "str", ")", ":", "\"\"\"\n Modify the name of the operator.\n\n :param name: name to be changed to\n \"\"\"", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "Error", ".", "ArgumentError", "(", "\"name must be a str!\"", ")", "self", ".", "_name", "=", "name", "@", "property", "def", "onSubSys", "(", "self", ")", ":", "\"\"\"\n Return the corresponding subsystem number of the operator.\n \"\"\"", "return", "self", ".", "_onSubSys", "@", "onSubSys", ".", "setter", "def", "onSubSys", "(", "self", ",", "onSubSys", ":", "int", ")", ":", "\"\"\"\n Modify the corresponding subsystem of the operator.\n\n :param onSubSys: subsystem to be changed to\n \"\"\"", "if", "onSubSys", "is", "None", ":", "self", ".", "_onSubSys", "=", "None", "else", ":", "if", "not", "isinstance", "(", "onSubSys", ",", "int", ")", ":", "raise", "Error", ".", "ArgumentError", "(", "f\"onSubSys must be an integer, instead of {type(onSubSys)}!\"", ")", "self", ".", "_onSubSys", "=", "onSubSys", "@", "property", "def", "coef", "(", "self", ")", ":", "\"\"\"\n Coefficient of the operator\n \"\"\"", "return", "self", ".", "_coef", "@", "coef", ".", "setter", "def", "coef", "(", "self", ",", "coef", ":", "Union", "[", "float", ",", "complex", "]", "=", "1.0", ")", ":", "\"\"\"\n Setter for the coefficient\n\n :param: coefficient to be set to\n \"\"\"", "if", "coef", "is", "None", ":", "self", ".", "_coef", "=", "1.0", "else", ":", "if", "not", "(", "isinstance", "(", "coef", ",", "float", ")", "or", "isinstance", "(", "coef", ",", "complex", ")", ")", ":", "raise", "Error", ".", "ArgumentError", "(", "f\"coef must be a float or complex, instead of {type(coef)}!\"", ")", "self", ".", "_coef", "=", "coef", "def", "dump", "(", "self", ")", "->", "str", ":", "\"\"\"\n Return base64 encoded string.\n\n :return: a base64 encoded string\n \"\"\"", "byteStr", "=", "pickle", ".", "dumps", "(", "self", ")", "base64str", "=", "base64", ".", "b64encode", "(", "byteStr", ")", "return", "base64str", ".", "decode", "(", ")", "@", "staticmethod", "def", "load", "(", "base64Str", ":", "str", ")", "->", "'QOperator'", ":", "\"\"\"\n Create object from base64 encoded string.\n\n :return: a QOperator object\n \"\"\"", "byteStr", "=", "base64", ".", "b64decode", "(", "base64Str", ".", "encode", "(", ")", ")", "obj", "=", "pickle", ".", "loads", "(", "byteStr", ")", "return", "obj" ]
In Quanlse, operators are stored in QOperator objects, which keep track of the operator's purpose, matrix form, coefficients and the qubits it corresponds to.
[ "In", "Quanlse", "operators", "are", "stored", "in", "QOperator", "objects", "which", "keep", "track", "of", "the", "operator", "'", "s", "purpose", "matrix", "form", "coefficients", "and", "the", "qubits", "it", "corresponds", "to", "." ]
[ "\"\"\"\n In Quanlse, operators are stored in QOperator objects, which keep track of the\n operator's purpose, matrix form, coefficients and the qubits it corresponds to.\n\n :param name: a user-given name\n :param matrix: corresponding matrix of the operator\n :param onSubSys: subsystem number\n :param coef: corresponding coefficient\n \"\"\"", "\"\"\"\n The constructor of the QOperator class.\n \"\"\"", "# type: str", "# type: ndarray", "# type: int", "# type: float", "\"\"\"\n Return the corresponding matrix (type: ndarray)\n \"\"\"", "\"\"\"\n Setter function for the matrix\n\n :param matrix: the matrix to be set to\n \"\"\"", "\"\"\"\n Return the corresponding name of the operator.\n \"\"\"", "\"\"\"\n Modify the name of the operator.\n\n :param name: name to be changed to\n \"\"\"", "\"\"\"\n Return the corresponding subsystem number of the operator.\n \"\"\"", "\"\"\"\n Modify the corresponding subsystem of the operator.\n\n :param onSubSys: subsystem to be changed to\n \"\"\"", "\"\"\"\n Coefficient of the operator\n \"\"\"", "\"\"\"\n Setter for the coefficient\n\n :param: coefficient to be set to\n \"\"\"", "\"\"\"\n Return base64 encoded string.\n\n :return: a base64 encoded string\n \"\"\"", "# Dump the object", "\"\"\"\n Create object from base64 encoded string.\n\n :return: a QOperator object\n \"\"\"", "# type: QOperator" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "name", "type": null, "docstring": "a user-given name", "docstring_tokens": [ "a", "user", "-", "given", "name" ], "default": null, "is_optional": null }, { "identifier": "matrix", "type": null, "docstring": "corresponding matrix of the operator", "docstring_tokens": [ "corresponding", "matrix", "of", "the", "operator" ], "default": null, "is_optional": null }, { "identifier": "onSubSys", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "coef", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "others": [] }
false
18
808
79
7c3a98dd0298c456b0a4f0fcfff759cb3da7ba73
aivclab/vision
samples/classification/ram/architecture/ram_modules.py
[ "Apache-2.0" ]
Python
Retina
A visual retina. Extracts a foveated glimpse `phi` around location `l` from an image `x`. Concretely, encodes the region around `l` at a high-resolution but uses a progressively lower resolution for pixels further from `l`, resulting in a compressed representation of the original image `x`. Args: x: a 4D Tensor of shape (B, H, W, C). The minibatch of images. l: a 2D Tensor of shape (B, 2). Contains normalized coordinates in the range [-1, 1]. size_first_patch: size of the first square patch. num_patches_per_glimpse: number of patches to extract in the glimpse. scale_factor_suc: scaling factor that controls the size of successive patches. Returns: phi: a 5D tensor of shape (B, k, g, g, C). The foveated glimpse of the image.
A visual retina. a 4D Tensor of shape (B, H, W, C). The minibatch of images. l: a 2D Tensor of shape (B, 2). Contains normalized coordinates in the range [-1, 1]. size_first_patch: size of the first square patch. num_patches_per_glimpse: number of patches to extract in the glimpse. scale_factor_suc: scaling factor that controls the size of successive patches. a 5D tensor of shape (B, k, g, g, C). The foveated glimpse of the image.
[ "A", "visual", "retina", ".", "a", "4D", "Tensor", "of", "shape", "(", "B", "H", "W", "C", ")", ".", "The", "minibatch", "of", "images", ".", "l", ":", "a", "2D", "Tensor", "of", "shape", "(", "B", "2", ")", ".", "Contains", "normalized", "coordinates", "in", "the", "range", "[", "-", "1", "1", "]", ".", "size_first_patch", ":", "size", "of", "the", "first", "square", "patch", ".", "num_patches_per_glimpse", ":", "number", "of", "patches", "to", "extract", "in", "the", "glimpse", ".", "scale_factor_suc", ":", "scaling", "factor", "that", "controls", "the", "size", "of", "successive", "patches", ".", "a", "5D", "tensor", "of", "shape", "(", "B", "k", "g", "g", "C", ")", ".", "The", "foveated", "glimpse", "of", "the", "image", "." ]
class Retina: """A visual retina. Extracts a foveated glimpse `phi` around location `l` from an image `x`. Concretely, encodes the region around `l` at a high-resolution but uses a progressively lower resolution for pixels further from `l`, resulting in a compressed representation of the original image `x`. Args: x: a 4D Tensor of shape (B, H, W, C). The minibatch of images. l: a 2D Tensor of shape (B, 2). Contains normalized coordinates in the range [-1, 1]. size_first_patch: size of the first square patch. num_patches_per_glimpse: number of patches to extract in the glimpse. scale_factor_suc: scaling factor that controls the size of successive patches. Returns: phi: a 5D tensor of shape (B, k, g, g, C). The foveated glimpse of the image.""" def __init__(self, size_first_patch, num_patches_per_glimpse, scale_factor_suc): self.g = size_first_patch self.k = num_patches_per_glimpse self.s = scale_factor_suc def foveate(self, x: torch.Tensor, l: torch.Tensor) -> torch.Tensor: """Extract `k` square patches of size `g`, centered at location `l`. The initial patch is a square of size `g`, and each subsequent patch is a square whose side is `s` times the size of the previous patch. The `k` patches are finally resized to (g, g) and concatenated into a tensor of shape (B, k, g, g, C).""" phi = [] size = self.g # extract k patches of increasing size for i in range(self.k): phi.append(self.extract_patch(x, l, size)) size = int(self.s * size) # resize the patches to squares of size g for i in range(1, len(phi)): k = phi[i].shape[-1] // self.g phi[i] = functional.avg_pool2d(phi[i], k) # concatenate into a single tensor and flatten phi = torch.cat(phi, 1) phi = phi.view(phi.shape[0], -1) return phi def extract_patch(self, x, l, size) -> torch.Tensor: """Extract a single patch for each image in `x`. Args: x: a 4D Tensor of shape (B, H, W, C). The minibatch of images. l: a 2D Tensor of shape (B, 2). size: a scalar defining the size of the extracted patch. Returns: patch: a 4D Tensor of shape (B, size, size, C)""" B, C, H, W = x.shape start = self.denormalize(H, l) end = start + size # pad with zeros x = functional.pad(x, (size // 2, size // 2, size // 2, size // 2)) # loop through mini-batch and extract patches patch = [] for i in range(B): patch.append(x[i, :, start[i, 1]: end[i, 1], start[i, 0]: end[i, 0]]) return torch.stack(patch) def denormalize(self, T, coords) -> torch.LongTensor: """Convert coordinates in the range [-1, 1] to coordinates in the range [0, T] where `T` is the size of the image.""" return (0.5 * ((coords + 1.0) * T)).long() def exceeds(self, from_x, to_x, from_y, to_y, T) -> bool: """Check whether the extracted patch will exceed the boundaries of the image of size `T`.""" if (from_x < 0) or (from_y < 0) or (to_x > T) or (to_y > T): return True return False
[ "class", "Retina", ":", "def", "__init__", "(", "self", ",", "size_first_patch", ",", "num_patches_per_glimpse", ",", "scale_factor_suc", ")", ":", "self", ".", "g", "=", "size_first_patch", "self", ".", "k", "=", "num_patches_per_glimpse", "self", ".", "s", "=", "scale_factor_suc", "def", "foveate", "(", "self", ",", "x", ":", "torch", ".", "Tensor", ",", "l", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "\"\"\"Extract `k` square patches of size `g`, centered\n at location `l`. The initial patch is a square of\n size `g`, and each subsequent patch is a square\n whose side is `s` times the size of the previous\n patch.\n\n The `k` patches are finally resized to (g, g) and\n concatenated into a tensor of shape (B, k, g, g, C).\"\"\"", "phi", "=", "[", "]", "size", "=", "self", ".", "g", "for", "i", "in", "range", "(", "self", ".", "k", ")", ":", "phi", ".", "append", "(", "self", ".", "extract_patch", "(", "x", ",", "l", ",", "size", ")", ")", "size", "=", "int", "(", "self", ".", "s", "*", "size", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "phi", ")", ")", ":", "k", "=", "phi", "[", "i", "]", ".", "shape", "[", "-", "1", "]", "//", "self", ".", "g", "phi", "[", "i", "]", "=", "functional", ".", "avg_pool2d", "(", "phi", "[", "i", "]", ",", "k", ")", "phi", "=", "torch", ".", "cat", "(", "phi", ",", "1", ")", "phi", "=", "phi", ".", "view", "(", "phi", ".", "shape", "[", "0", "]", ",", "-", "1", ")", "return", "phi", "def", "extract_patch", "(", "self", ",", "x", ",", "l", ",", "size", ")", "->", "torch", ".", "Tensor", ":", "\"\"\"Extract a single patch for each image in `x`.\n\n Args:\n x: a 4D Tensor of shape (B, H, W, C). The minibatch\n of images.\n l: a 2D Tensor of shape (B, 2).\n size: a scalar defining the size of the extracted patch.\n\n Returns:\n patch: a 4D Tensor of shape (B, size, size, C)\"\"\"", "B", ",", "C", ",", "H", ",", "W", "=", "x", ".", "shape", "start", "=", "self", ".", "denormalize", "(", "H", ",", "l", ")", "end", "=", "start", "+", "size", "x", "=", "functional", ".", "pad", "(", "x", ",", "(", "size", "//", "2", ",", "size", "//", "2", ",", "size", "//", "2", ",", "size", "//", "2", ")", ")", "patch", "=", "[", "]", "for", "i", "in", "range", "(", "B", ")", ":", "patch", ".", "append", "(", "x", "[", "i", ",", ":", ",", "start", "[", "i", ",", "1", "]", ":", "end", "[", "i", ",", "1", "]", ",", "start", "[", "i", ",", "0", "]", ":", "end", "[", "i", ",", "0", "]", "]", ")", "return", "torch", ".", "stack", "(", "patch", ")", "def", "denormalize", "(", "self", ",", "T", ",", "coords", ")", "->", "torch", ".", "LongTensor", ":", "\"\"\"Convert coordinates in the range [-1, 1] to\n coordinates in the range [0, T] where `T` is\n the size of the image.\"\"\"", "return", "(", "0.5", "*", "(", "(", "coords", "+", "1.0", ")", "*", "T", ")", ")", ".", "long", "(", ")", "def", "exceeds", "(", "self", ",", "from_x", ",", "to_x", ",", "from_y", ",", "to_y", ",", "T", ")", "->", "bool", ":", "\"\"\"Check whether the extracted patch will exceed\n the boundaries of the image of size `T`.\"\"\"", "if", "(", "from_x", "<", "0", ")", "or", "(", "from_y", "<", "0", ")", "or", "(", "to_x", ">", "T", ")", "or", "(", "to_y", ">", "T", ")", ":", "return", "True", "return", "False" ]
A visual retina.
[ "A", "visual", "retina", "." ]
[ "\"\"\"A visual retina.\n\n Extracts a foveated glimpse `phi` around location `l`\n from an image `x`.\n\n Concretely, encodes the region around `l` at a\n high-resolution but uses a progressively lower\n resolution for pixels further from `l`, resulting\n in a compressed representation of the original\n image `x`.\n\n Args:\n x: a 4D Tensor of shape (B, H, W, C). The minibatch\n of images.\n l: a 2D Tensor of shape (B, 2). Contains normalized\n coordinates in the range [-1, 1].\n size_first_patch: size of the first square patch.\n num_patches_per_glimpse: number of patches to extract in the glimpse.\n scale_factor_suc: scaling factor that controls the size of\n successive patches.\n\n Returns:\n phi: a 5D tensor of shape (B, k, g, g, C). The\n foveated glimpse of the image.\"\"\"", "\"\"\"Extract `k` square patches of size `g`, centered\n at location `l`. The initial patch is a square of\n size `g`, and each subsequent patch is a square\n whose side is `s` times the size of the previous\n patch.\n\n The `k` patches are finally resized to (g, g) and\n concatenated into a tensor of shape (B, k, g, g, C).\"\"\"", "# extract k patches of increasing size", "# resize the patches to squares of size g", "# concatenate into a single tensor and flatten", "\"\"\"Extract a single patch for each image in `x`.\n\n Args:\n x: a 4D Tensor of shape (B, H, W, C). The minibatch\n of images.\n l: a 2D Tensor of shape (B, 2).\n size: a scalar defining the size of the extracted patch.\n\n Returns:\n patch: a 4D Tensor of shape (B, size, size, C)\"\"\"", "# pad with zeros", "# loop through mini-batch and extract patches", "\"\"\"Convert coordinates in the range [-1, 1] to\n coordinates in the range [0, T] where `T` is\n the size of the image.\"\"\"", "\"\"\"Check whether the extracted patch will exceed\n the boundaries of the image of size `T`.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
921
220
2e84ae9a62af3a06829b6e66002c5edac454198b
NetanSolutions/node-powershell-x86
src/Shell.js
[ "MIT" ]
JavaScript
Shell
/** * The Shell class. * * @constructor * @param {Object} config The config for the shell instance. https://github.com/rannn505/node-powershell#initializeconstructor * @returns {Shell} A Shell instance which allows you to run PowerShell commands from your NodeJS app. * It exposes a simple API that bridges between your node and a PS child process. */
The Shell class. @constructor @param {Object} config The config for the shell instance.
[ "The", "Shell", "class", ".", "@constructor", "@param", "{", "Object", "}", "config", "The", "config", "for", "the", "shell", "instance", "." ]
class Shell extends EventEmitter { constructor({ inputEncoding: inputEncoding = 'utf8', outputEncoding: outputEncoding = 'utf8', debugMsg: debugMsg = true, verbose: verbose = true, executionPolicy: executionPolicy = 'Unrestricted', noProfile: noProfile = true, EOI: EOI = 'EOI', version } = {}) { super(); // cmds bulk to run at the next invoke call this._cmds = []; // history of cmds this._history = []; // global config for class this._cfg = {}; this._cfg.verbose = debugMsg && verbose; this._cfg.EOI = EOI; // arguments for PowerShell process let args = ['-NoLogo', '-NoExit', '-InputFormat', 'Text', '-Command', '-']; if(noProfile) { args = ['-NoProfile', ...args]; } if(IS_WIN) { args = ['-ExecutionPolicy', executionPolicy, ...args]; } if(version) { args = ['-Version', version, ...args]; } // the PowerShell process this._proc = spawn(`%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell${IS_WIN ? '.exe' : ''}`, args, { stdio: 'pipe' }); // Make sure the PS process start successfully if(!this._proc.pid) { throw new Error(MSGS.INIT.ERROR.START_PS); } this._proc.on('error', error => { throw new Error(MSGS.INIT.ERROR.START_PS); }); // Set streams encoding this._proc.stdin.setDefaultEncoding(inputEncoding); this._proc.stdout.setEncoding(outputEncoding); this._proc.stderr.setEncoding(outputEncoding); // handle current output const output = new ShellStream(this._cfg.EOI); let hasError = false; this._proc.stdout.pipe(output); this._proc.stderr.pipe(output); this._proc.stderr.on('data', (data) => { hasError = true; }); this._proc.on('close', code => { this.emit('end', code); let exitMsg = `Process ${this._proc.pid} exited with code ${code}\n`; if(hasError) { // PS process failed to start this._print(ERROR_MSG(exitMsg)); // this._print(ERROR_MSG(Buffer.concat(output.stdout).toString())); throw new Error(Buffer.concat(output.stdout).toString().replace(/\0/g, '')); } else { // dispose if(code !== 0) { this._print(ERROR_MSG(exitMsg)); this._reject(ERROR_MSG(`script exit ${code}`)); } else { this._print(OK_MSG(exitMsg)); this._resolve(`script exit ${code}`); } } }); output.on('EOI', (data) => { if(hasError) { this.emit('err', data); this._print(MSGS.INVOKE.ERROR.CMD_FAIL); this._reject(ERROR_MSG(data)); } else { this.emit('output', data); this._print(MSGS.INVOKE.OK.CMD_FINISH); this._resolve(data); } hasError = false; }); // public props this.history = this._history; this.streams = { stdin: this._proc.stdin, stdout: this._proc.stdout, stderr: this._proc.stderr }; this._print(OK_MSG(`Process ${this._proc.pid} started\n`)); } _print(msg) { this._cfg.verbose && console.log(`${MODULE_MSG} ${msg}`); } addCommand(command, params = []) { return new Promise((resolve, reject) => { if(!command) { return reject(MSGS.ADD_COMMAND.ERROR.CMD_MISS); } if(!Array.isArray(params)) { return reject(MSGS.ADD_COMMAND.ERROR.PARAMS_TYPE); } let cmdStr = `${command}`; for (const param of params) { let paramType = Object.prototype.toString.call(param).slice(8, -1); if(paramType === 'Object') { // param is {name: '', value: ''} or {name: value} let paramKeys = Object.keys(param); let paramName, paramValue; if(paramKeys.length === 2 && paramKeys[0] === 'name' && paramKeys[1] === 'value') { // param is {name: '', value: ''} paramName = param.name; paramValue = param.value; } else if(paramKeys.length === 1 && paramKeys[0]) { // param is {name: value} paramName = paramKeys[0]; paramValue = param[paramName]; } else { return reject(MSGS.ADD_COMMAND.ERROR.PARAM_STRUCT); } // cast a parameter value from JS data types to PowerShell data types. paramValue = toPS(paramValue); // determine whether @ syntax used in cmd let isReplaced = false; cmdStr = cmdStr.replace(`@${paramName}`, match => { isReplaced = true; return `-${paramName} ${paramValue}` }); if(!isReplaced) { cmdStr = cmdStr.concat(` -${paramName}${paramValue ? ' ' + paramValue : ''}`); } } else if(paramType === 'String') { // param is switch cmdStr = cmdStr.concat(` -${param}`); } else { return reject(MSGS.ADD_COMMAND.ERROR.PARAM_TYPE); } } this._cmds.push(cmdStr); this._history.push(cmdStr); resolve(this._cmds); }); } invoke() { return new Promise((resolve, reject) => { // Make resolve, reject accessible to the class this._resolve = resolve; this._reject = reject; let cmdsStr = this._cmds.join('; '); ShellWrite(this._proc.stdin, cmdsStr) .then(() => ShellWrite(this._proc.stdin, os.EOL)) .then(() => ShellWrite(this._proc.stdin, `echo ${this._cfg.EOI}`)) .then(() => ShellWrite(this._proc.stdin, os.EOL)); this._print(MSGS.INVOKE.OK.CMD_START); this._print(INFO_MSG(cmdsStr)); // this._cfg.verbose && console.log(` ${colors.gray(cmdsStr)}`); this._cmds = []; }); } dispose() { return new Promise((resolve, reject) => { // Make resolve, reject accessible to the class this._resolve = resolve; this._reject = reject; ShellWrite(this._proc.stdin, 'exit') .then(() => ShellWrite(this._proc.stdin, os.EOL)) .then(() => this._proc.stdin.end()) }); } }
[ "class", "Shell", "extends", "EventEmitter", "{", "constructor", "(", "{", "inputEncoding", ":", "inputEncoding", "=", "'utf8'", ",", "outputEncoding", ":", "outputEncoding", "=", "'utf8'", ",", "debugMsg", ":", "debugMsg", "=", "true", ",", "verbose", ":", "verbose", "=", "true", ",", "executionPolicy", ":", "executionPolicy", "=", "'Unrestricted'", ",", "noProfile", ":", "noProfile", "=", "true", ",", "EOI", ":", "EOI", "=", "'EOI'", ",", "version", "}", "=", "{", "}", ")", "{", "super", "(", ")", ";", "this", ".", "_cmds", "=", "[", "]", ";", "this", ".", "_history", "=", "[", "]", ";", "this", ".", "_cfg", "=", "{", "}", ";", "this", ".", "_cfg", ".", "verbose", "=", "debugMsg", "&&", "verbose", ";", "this", ".", "_cfg", ".", "EOI", "=", "EOI", ";", "let", "args", "=", "[", "'-NoLogo'", ",", "'-NoExit'", ",", "'-InputFormat'", ",", "'Text'", ",", "'-Command'", ",", "'-'", "]", ";", "if", "(", "noProfile", ")", "{", "args", "=", "[", "'-NoProfile'", ",", "...", "args", "]", ";", "}", "if", "(", "IS_WIN", ")", "{", "args", "=", "[", "'-ExecutionPolicy'", ",", "executionPolicy", ",", "...", "args", "]", ";", "}", "if", "(", "version", ")", "{", "args", "=", "[", "'-Version'", ",", "version", ",", "...", "args", "]", ";", "}", "this", ".", "_proc", "=", "spawn", "(", "`", "\\s", "\\W", "\\v", "\\p", "${", "IS_WIN", "?", "'.exe'", ":", "''", "}", "`", ",", "args", ",", "{", "stdio", ":", "'pipe'", "}", ")", ";", "if", "(", "!", "this", ".", "_proc", ".", "pid", ")", "{", "throw", "new", "Error", "(", "MSGS", ".", "INIT", ".", "ERROR", ".", "START_PS", ")", ";", "}", "this", ".", "_proc", ".", "on", "(", "'error'", ",", "error", "=>", "{", "throw", "new", "Error", "(", "MSGS", ".", "INIT", ".", "ERROR", ".", "START_PS", ")", ";", "}", ")", ";", "this", ".", "_proc", ".", "stdin", ".", "setDefaultEncoding", "(", "inputEncoding", ")", ";", "this", ".", "_proc", ".", "stdout", ".", "setEncoding", "(", "outputEncoding", ")", ";", "this", ".", "_proc", ".", "stderr", ".", "setEncoding", "(", "outputEncoding", ")", ";", "const", "output", "=", "new", "ShellStream", "(", "this", ".", "_cfg", ".", "EOI", ")", ";", "let", "hasError", "=", "false", ";", "this", ".", "_proc", ".", "stdout", ".", "pipe", "(", "output", ")", ";", "this", ".", "_proc", ".", "stderr", ".", "pipe", "(", "output", ")", ";", "this", ".", "_proc", ".", "stderr", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "hasError", "=", "true", ";", "}", ")", ";", "this", ".", "_proc", ".", "on", "(", "'close'", ",", "code", "=>", "{", "this", ".", "emit", "(", "'end'", ",", "code", ")", ";", "let", "exitMsg", "=", "`", "${", "this", ".", "_proc", ".", "pid", "}", "${", "code", "}", "\\n", "`", ";", "if", "(", "hasError", ")", "{", "this", ".", "_print", "(", "ERROR_MSG", "(", "exitMsg", ")", ")", ";", "throw", "new", "Error", "(", "Buffer", ".", "concat", "(", "output", ".", "stdout", ")", ".", "toString", "(", ")", ".", "replace", "(", "/", "\\0", "/", "g", ",", "''", ")", ")", ";", "}", "else", "{", "if", "(", "code", "!==", "0", ")", "{", "this", ".", "_print", "(", "ERROR_MSG", "(", "exitMsg", ")", ")", ";", "this", ".", "_reject", "(", "ERROR_MSG", "(", "`", "${", "code", "}", "`", ")", ")", ";", "}", "else", "{", "this", ".", "_print", "(", "OK_MSG", "(", "exitMsg", ")", ")", ";", "this", ".", "_resolve", "(", "`", "${", "code", "}", "`", ")", ";", "}", "}", "}", ")", ";", "output", ".", "on", "(", "'EOI'", ",", "(", "data", ")", "=>", "{", "if", "(", "hasError", ")", "{", "this", ".", "emit", "(", "'err'", ",", "data", ")", ";", "this", ".", "_print", "(", "MSGS", ".", "INVOKE", ".", "ERROR", ".", "CMD_FAIL", ")", ";", "this", ".", "_reject", "(", "ERROR_MSG", "(", "data", ")", ")", ";", "}", "else", "{", "this", ".", "emit", "(", "'output'", ",", "data", ")", ";", "this", ".", "_print", "(", "MSGS", ".", "INVOKE", ".", "OK", ".", "CMD_FINISH", ")", ";", "this", ".", "_resolve", "(", "data", ")", ";", "}", "hasError", "=", "false", ";", "}", ")", ";", "this", ".", "history", "=", "this", ".", "_history", ";", "this", ".", "streams", "=", "{", "stdin", ":", "this", ".", "_proc", ".", "stdin", ",", "stdout", ":", "this", ".", "_proc", ".", "stdout", ",", "stderr", ":", "this", ".", "_proc", ".", "stderr", "}", ";", "this", ".", "_print", "(", "OK_MSG", "(", "`", "${", "this", ".", "_proc", ".", "pid", "}", "\\n", "`", ")", ")", ";", "}", "_print", "(", "msg", ")", "{", "this", ".", "_cfg", ".", "verbose", "&&", "console", ".", "log", "(", "`", "${", "MODULE_MSG", "}", "${", "msg", "}", "`", ")", ";", "}", "addCommand", "(", "command", ",", "params", "=", "[", "]", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "command", ")", "{", "return", "reject", "(", "MSGS", ".", "ADD_COMMAND", ".", "ERROR", ".", "CMD_MISS", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "params", ")", ")", "{", "return", "reject", "(", "MSGS", ".", "ADD_COMMAND", ".", "ERROR", ".", "PARAMS_TYPE", ")", ";", "}", "let", "cmdStr", "=", "`", "${", "command", "}", "`", ";", "for", "(", "const", "param", "of", "params", ")", "{", "let", "paramType", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "param", ")", ".", "slice", "(", "8", ",", "-", "1", ")", ";", "if", "(", "paramType", "===", "'Object'", ")", "{", "let", "paramKeys", "=", "Object", ".", "keys", "(", "param", ")", ";", "let", "paramName", ",", "paramValue", ";", "if", "(", "paramKeys", ".", "length", "===", "2", "&&", "paramKeys", "[", "0", "]", "===", "'name'", "&&", "paramKeys", "[", "1", "]", "===", "'value'", ")", "{", "paramName", "=", "param", ".", "name", ";", "paramValue", "=", "param", ".", "value", ";", "}", "else", "if", "(", "paramKeys", ".", "length", "===", "1", "&&", "paramKeys", "[", "0", "]", ")", "{", "paramName", "=", "paramKeys", "[", "0", "]", ";", "paramValue", "=", "param", "[", "paramName", "]", ";", "}", "else", "{", "return", "reject", "(", "MSGS", ".", "ADD_COMMAND", ".", "ERROR", ".", "PARAM_STRUCT", ")", ";", "}", "paramValue", "=", "toPS", "(", "paramValue", ")", ";", "let", "isReplaced", "=", "false", ";", "cmdStr", "=", "cmdStr", ".", "replace", "(", "`", "${", "paramName", "}", "`", ",", "match", "=>", "{", "isReplaced", "=", "true", ";", "return", "`", "${", "paramName", "}", "${", "paramValue", "}", "`", "}", ")", ";", "if", "(", "!", "isReplaced", ")", "{", "cmdStr", "=", "cmdStr", ".", "concat", "(", "`", "${", "paramName", "}", "${", "paramValue", "?", "' '", "+", "paramValue", ":", "''", "}", "`", ")", ";", "}", "}", "else", "if", "(", "paramType", "===", "'String'", ")", "{", "cmdStr", "=", "cmdStr", ".", "concat", "(", "`", "${", "param", "}", "`", ")", ";", "}", "else", "{", "return", "reject", "(", "MSGS", ".", "ADD_COMMAND", ".", "ERROR", ".", "PARAM_TYPE", ")", ";", "}", "}", "this", ".", "_cmds", ".", "push", "(", "cmdStr", ")", ";", "this", ".", "_history", ".", "push", "(", "cmdStr", ")", ";", "resolve", "(", "this", ".", "_cmds", ")", ";", "}", ")", ";", "}", "invoke", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "this", ".", "_resolve", "=", "resolve", ";", "this", ".", "_reject", "=", "reject", ";", "let", "cmdsStr", "=", "this", ".", "_cmds", ".", "join", "(", "'; '", ")", ";", "ShellWrite", "(", "this", ".", "_proc", ".", "stdin", ",", "cmdsStr", ")", ".", "then", "(", "(", ")", "=>", "ShellWrite", "(", "this", ".", "_proc", ".", "stdin", ",", "os", ".", "EOL", ")", ")", ".", "then", "(", "(", ")", "=>", "ShellWrite", "(", "this", ".", "_proc", ".", "stdin", ",", "`", "${", "this", ".", "_cfg", ".", "EOI", "}", "`", ")", ")", ".", "then", "(", "(", ")", "=>", "ShellWrite", "(", "this", ".", "_proc", ".", "stdin", ",", "os", ".", "EOL", ")", ")", ";", "this", ".", "_print", "(", "MSGS", ".", "INVOKE", ".", "OK", ".", "CMD_START", ")", ";", "this", ".", "_print", "(", "INFO_MSG", "(", "cmdsStr", ")", ")", ";", "this", ".", "_cmds", "=", "[", "]", ";", "}", ")", ";", "}", "dispose", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "this", ".", "_resolve", "=", "resolve", ";", "this", ".", "_reject", "=", "reject", ";", "ShellWrite", "(", "this", ".", "_proc", ".", "stdin", ",", "'exit'", ")", ".", "then", "(", "(", ")", "=>", "ShellWrite", "(", "this", ".", "_proc", ".", "stdin", ",", "os", ".", "EOL", ")", ")", ".", "then", "(", "(", ")", "=>", "this", ".", "_proc", ".", "stdin", ".", "end", "(", ")", ")", "}", ")", ";", "}", "}" ]
The Shell class.
[ "The", "Shell", "class", "." ]
[ "// cmds bulk to run at the next invoke call", "// history of cmds", "// global config for class", "// arguments for PowerShell process", "// the PowerShell process", "// Make sure the PS process start successfully", "// Set streams encoding", "// handle current output", "// PS process failed to start", "// this._print(ERROR_MSG(Buffer.concat(output.stdout).toString()));", "// dispose", "// public props", "// param is {name: '', value: ''} or {name: value}", "// param is {name: '', value: ''}", "// param is {name: value}", "// cast a parameter value from JS data types to PowerShell data types.", "// determine whether @ syntax used in cmd", "// param is switch", "// Make resolve, reject accessible to the class", "// this._cfg.verbose && console.log(` ${colors.gray(cmdsStr)}`);", "// Make resolve, reject accessible to the class" ]
[ { "param": "EventEmitter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EventEmitter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
25
1,479
83
e3c3656cf9a4866e0ab8acb2072fbb4db3f74437
singhaditya28/fs_image
fs_image/rpm/yum_dnf_conf.py
[ "MIT" ]
Python
YumDnfConfIsolator
The functions in this class ATTEMPT to edit `{yum,dnf}.conf` in such a way that the package manager will: - never interact with state, caches, or configuration from the host filesystem, - never interact with servers outside of the ones we specify. As per the file-docblock note, `dnf` isolation is likely incomplete. IMPORTANT: With `yum`, it is actually impossible to configure it such that it does not touch the host filesystem. A couple of specific examples: (1) Regardless of the configuration, `yum` will look in `$host_root/$cachedir` BEFORE `$installroot/$cachedir`, which is breaks isolation of RPM content and repodata. (2) Regardless of the configuration, `yum` will attempt to read `/etc/yum/vars` from the host, breaking isolation of configuration. There are other examples. To see the bind-mount protections we use to avoid leakage from the host, read `_isolate_yum_dnf_and_wait_until_ready` -- and of course, the larger purpose of `yum-dnf-from-snapshot` is to run its `yum` or `dnf` inside a private network namespace to guarantee no off-host repo accesses.
The functions in this class ATTEMPT to edit `{yum,dnf}.conf` in such a way that the package manager will: never interact with state, caches, or configuration from the host filesystem, never interact with servers outside of the ones we specify. As per the file-docblock note, `dnf` isolation is likely incomplete. With `yum`, it is actually impossible to configure it such that it does not touch the host filesystem. A couple of specific examples. (2) Regardless of the configuration, `yum` will attempt to read `/etc/yum/vars` from the host, breaking isolation of configuration. There are other examples.
[ "The", "functions", "in", "this", "class", "ATTEMPT", "to", "edit", "`", "{", "yum", "dnf", "}", ".", "conf", "`", "in", "such", "a", "way", "that", "the", "package", "manager", "will", ":", "never", "interact", "with", "state", "caches", "or", "configuration", "from", "the", "host", "filesystem", "never", "interact", "with", "servers", "outside", "of", "the", "ones", "we", "specify", ".", "As", "per", "the", "file", "-", "docblock", "note", "`", "dnf", "`", "isolation", "is", "likely", "incomplete", ".", "With", "`", "yum", "`", "it", "is", "actually", "impossible", "to", "configure", "it", "such", "that", "it", "does", "not", "touch", "the", "host", "filesystem", ".", "A", "couple", "of", "specific", "examples", ".", "(", "2", ")", "Regardless", "of", "the", "configuration", "`", "yum", "`", "will", "attempt", "to", "read", "`", "/", "etc", "/", "yum", "/", "vars", "`", "from", "the", "host", "breaking", "isolation", "of", "configuration", ".", "There", "are", "other", "examples", "." ]
class YumDnfConfIsolator: ''' The functions in this class ATTEMPT to edit `{yum,dnf}.conf` in such a way that the package manager will: - never interact with state, caches, or configuration from the host filesystem, - never interact with servers outside of the ones we specify. As per the file-docblock note, `dnf` isolation is likely incomplete. IMPORTANT: With `yum`, it is actually impossible to configure it such that it does not touch the host filesystem. A couple of specific examples: (1) Regardless of the configuration, `yum` will look in `$host_root/$cachedir` BEFORE `$installroot/$cachedir`, which is breaks isolation of RPM content and repodata. (2) Regardless of the configuration, `yum` will attempt to read `/etc/yum/vars` from the host, breaking isolation of configuration. There are other examples. To see the bind-mount protections we use to avoid leakage from the host, read `_isolate_yum_dnf_and_wait_until_ready` -- and of course, the larger purpose of `yum-dnf-from-snapshot` is to run its `yum` or `dnf` inside a private network namespace to guarantee no off-host repo accesses. ''' def __init__(self, yum_dnf: YumDnf, cp: ConfigParser): self._yum_dnf = yum_dnf self._cp = ConfigParser() self._cp.read_dict(cp) # Make a copy self._isolated_main = False self._isolated_repos = False def isolate_repos( self, repos: Iterable[YumDnfConfRepo], ) -> 'YumDnfConfIsolator': ''' Asserts that the passed repos are exactly those defined in the config file. This ensures that we leave no repo unisolated. For each specified repo, sets the config values specified in its `YumDnfConfRepo`, and clears `proxy`. Other config keys are left unchanged -- but seeing some "known bad" configs in the config file will cause an assertion error. IMPORTANT: See the class docblock, this is not **ENOUGH**. ''' unchanged_repos = {r for r in self._cp if r not in _NON_REPO_SECTIONS} for repo in repos: unchanged_repos.remove(repo.name) assert repo.name not in _NON_REPO_SECTIONS repo_sec = self._cp[repo.name] repo_sec['baseurl'] = '\n'.join(repo.base_url) \ if isinstance(repo.base_url, list) else repo.base_url repo_sec['gpgkey'] = '\n'.join(repo.gpg_key_urls) repo_sec.pop('proxy', None) # We talk only to a local reposerver. # These are not handled for now, but could be supported. The # goal of asserting their absence is to avoid accidentally # having non-isolated URLs in the config. for unsupported_key in [ 'include', 'metalink', 'mirrorlist', 'gpgcakey' ]: assert unsupported_key not in repo_sec, (unsupported_key, repo) # NB: As with [main], we let the SSL-related options come # from the host: `sslcacert`, `sslclientcert`, and `sslclientkey` assert not unchanged_repos, f'Failed to isolate {unchanged_repos}' self._isolated_repos = True return self def isolate_main( self, *, config_path: str, versionlock_dir: str, ) -> 'YumDnfConfIsolator': ''' Set keys that could cause `yum` or `dnf` to interact with the host filesystem. IMPORTANT: See the class docblock, this is not ENOUGH. ''' prog_name = self._yum_dnf.value main_sec = self._cp['main'] assert ( 'include' not in main_sec and 'include' not in self._cp['DEFAULT'] ), 'Includes are not supported' # This list was obtained by scrolling through `man yum.conf`. To be # really thorough, we'd also remove glob filesystem dependencies # from options like `exclude`, `includepkgs`, `protected_packages`, # `exactarchlist`, etc -- but this is a moot point now that all RPM # installs go trough a build appliance. # # `cachedir` and `persistdir` are under `--installroot`, so no # isolation needed. However, ensuring defaults makes later # container customization (e.g. cleanup) easier. These can be # optionalized later if a good reason arises. In that case, # remember that `RpmActionItem` has special handling for `cachedir`. main_sec['cachedir'] = f'/var/cache/{prog_name}' # default main_sec['persistdir'] = f'/var/lib/{prog_name}' # default # Specify repos only via this `.conf` -- that eases isolating them. main_sec['reposdir'] = '/dev/null' # See the note about `cachedir` -- the same logic applies. main_sec['logfile'] = f'/var/log/{prog_name}.log' # default main_sec['config_file_path'] = config_path # Our download path isn't very fast, nor are the CI hosts. So, we make # the fetch timeout higher than might be desired on bare-metal hosts. main_sec['timeout'] = '60' main_sec.pop('proxy', None) # We talk only to a local reposerver. # NB: `sslcacert`, `sslclientcert`, and `sslclientkey` are left # as-is, though these read from the host filesystem. # Allowing arbitrary plugins could easily break isolation, but we # are actually only allowing our custom versionlock here. main_sec['plugins'] = '1' main_sec['pluginpath'] = versionlock_dir main_sec['pluginconfpath'] = versionlock_dir # This option seems to only exist for `dnf`. main_sec['varsdir'] = '/dev/null' # This final block of options seems only to exist for `yum`. # # Shouldn't make a difference for as-root runs, but it's good hygiene main_sec['usercache'] = '0' main_sec['syslog_device'] = '' # We'll just use `logfile`. main_sec['bugtracker_url'] = '' main_sec['fssnap_devices'] = '!*' # Snapshots don't make sense. assert not main_sec.get('commands') # This option seems dodgy. # Make yum fail if one package in a list can't be installed. if self._yum_dnf == YumDnf.yum: main_sec['skip_missing_names_on_install'] = '0' main_sec['skip_missing_names_on_update'] = '0' self._isolated_main = True return self def write(self, out: TextIO): 'Outputs a `{yum,dnf}.conf` file with the changed configuration.' assert self._isolated_main and self._isolated_repos self._cp.write(out)
[ "class", "YumDnfConfIsolator", ":", "def", "__init__", "(", "self", ",", "yum_dnf", ":", "YumDnf", ",", "cp", ":", "ConfigParser", ")", ":", "self", ".", "_yum_dnf", "=", "yum_dnf", "self", ".", "_cp", "=", "ConfigParser", "(", ")", "self", ".", "_cp", ".", "read_dict", "(", "cp", ")", "self", ".", "_isolated_main", "=", "False", "self", ".", "_isolated_repos", "=", "False", "def", "isolate_repos", "(", "self", ",", "repos", ":", "Iterable", "[", "YumDnfConfRepo", "]", ",", ")", "->", "'YumDnfConfIsolator'", ":", "'''\n Asserts that the passed repos are exactly those defined in the\n config file. This ensures that we leave no repo unisolated.\n\n For each specified repo, sets the config values specified in its\n `YumDnfConfRepo`, and clears `proxy`. Other config keys are left\n unchanged -- but seeing some \"known bad\" configs in the config file\n will cause an assertion error.\n\n IMPORTANT: See the class docblock, this is not **ENOUGH**.\n '''", "unchanged_repos", "=", "{", "r", "for", "r", "in", "self", ".", "_cp", "if", "r", "not", "in", "_NON_REPO_SECTIONS", "}", "for", "repo", "in", "repos", ":", "unchanged_repos", ".", "remove", "(", "repo", ".", "name", ")", "assert", "repo", ".", "name", "not", "in", "_NON_REPO_SECTIONS", "repo_sec", "=", "self", ".", "_cp", "[", "repo", ".", "name", "]", "repo_sec", "[", "'baseurl'", "]", "=", "'\\n'", ".", "join", "(", "repo", ".", "base_url", ")", "if", "isinstance", "(", "repo", ".", "base_url", ",", "list", ")", "else", "repo", ".", "base_url", "repo_sec", "[", "'gpgkey'", "]", "=", "'\\n'", ".", "join", "(", "repo", ".", "gpg_key_urls", ")", "repo_sec", ".", "pop", "(", "'proxy'", ",", "None", ")", "for", "unsupported_key", "in", "[", "'include'", ",", "'metalink'", ",", "'mirrorlist'", ",", "'gpgcakey'", "]", ":", "assert", "unsupported_key", "not", "in", "repo_sec", ",", "(", "unsupported_key", ",", "repo", ")", "assert", "not", "unchanged_repos", ",", "f'Failed to isolate {unchanged_repos}'", "self", ".", "_isolated_repos", "=", "True", "return", "self", "def", "isolate_main", "(", "self", ",", "*", ",", "config_path", ":", "str", ",", "versionlock_dir", ":", "str", ",", ")", "->", "'YumDnfConfIsolator'", ":", "'''\n Set keys that could cause `yum` or `dnf` to interact with the host\n filesystem. IMPORTANT: See the class docblock, this is not ENOUGH.\n '''", "prog_name", "=", "self", ".", "_yum_dnf", ".", "value", "main_sec", "=", "self", ".", "_cp", "[", "'main'", "]", "assert", "(", "'include'", "not", "in", "main_sec", "and", "'include'", "not", "in", "self", ".", "_cp", "[", "'DEFAULT'", "]", ")", ",", "'Includes are not supported'", "main_sec", "[", "'cachedir'", "]", "=", "f'/var/cache/{prog_name}'", "main_sec", "[", "'persistdir'", "]", "=", "f'/var/lib/{prog_name}'", "main_sec", "[", "'reposdir'", "]", "=", "'/dev/null'", "main_sec", "[", "'logfile'", "]", "=", "f'/var/log/{prog_name}.log'", "main_sec", "[", "'config_file_path'", "]", "=", "config_path", "main_sec", "[", "'timeout'", "]", "=", "'60'", "main_sec", ".", "pop", "(", "'proxy'", ",", "None", ")", "main_sec", "[", "'plugins'", "]", "=", "'1'", "main_sec", "[", "'pluginpath'", "]", "=", "versionlock_dir", "main_sec", "[", "'pluginconfpath'", "]", "=", "versionlock_dir", "main_sec", "[", "'varsdir'", "]", "=", "'/dev/null'", "main_sec", "[", "'usercache'", "]", "=", "'0'", "main_sec", "[", "'syslog_device'", "]", "=", "''", "main_sec", "[", "'bugtracker_url'", "]", "=", "''", "main_sec", "[", "'fssnap_devices'", "]", "=", "'!*'", "assert", "not", "main_sec", ".", "get", "(", "'commands'", ")", "if", "self", ".", "_yum_dnf", "==", "YumDnf", ".", "yum", ":", "main_sec", "[", "'skip_missing_names_on_install'", "]", "=", "'0'", "main_sec", "[", "'skip_missing_names_on_update'", "]", "=", "'0'", "self", ".", "_isolated_main", "=", "True", "return", "self", "def", "write", "(", "self", ",", "out", ":", "TextIO", ")", ":", "'Outputs a `{yum,dnf}.conf` file with the changed configuration.'", "assert", "self", ".", "_isolated_main", "and", "self", ".", "_isolated_repos", "self", ".", "_cp", ".", "write", "(", "out", ")" ]
The functions in this class ATTEMPT to edit `{yum,dnf}.conf` in such a way that the package manager will: never interact with state, caches, or configuration from the host filesystem, never interact with servers outside of the ones we specify.
[ "The", "functions", "in", "this", "class", "ATTEMPT", "to", "edit", "`", "{", "yum", "dnf", "}", ".", "conf", "`", "in", "such", "a", "way", "that", "the", "package", "manager", "will", ":", "never", "interact", "with", "state", "caches", "or", "configuration", "from", "the", "host", "filesystem", "never", "interact", "with", "servers", "outside", "of", "the", "ones", "we", "specify", "." ]
[ "'''\n The functions in this class ATTEMPT to edit `{yum,dnf}.conf` in such a\n way that the package manager will:\n - never interact with state, caches, or configuration from the host\n filesystem,\n - never interact with servers outside of the ones we specify.\n\n As per the file-docblock note, `dnf` isolation is likely incomplete.\n\n IMPORTANT: With `yum`, it is actually impossible to configure it such\n that it does not touch the host filesystem. A couple of specific\n examples:\n\n (1) Regardless of the configuration, `yum` will look in\n `$host_root/$cachedir` BEFORE `$installroot/$cachedir`, which is\n breaks isolation of RPM content and repodata.\n\n (2) Regardless of the configuration, `yum` will attempt to read\n `/etc/yum/vars` from the host, breaking isolation of configuration.\n\n There are other examples. To see the bind-mount protections we use to\n avoid leakage from the host, read `_isolate_yum_dnf_and_wait_until_ready` --\n and of course, the larger purpose of `yum-dnf-from-snapshot` is to run\n its `yum` or `dnf` inside a private network namespace to guarantee no\n off-host repo accesses.\n '''", "# Make a copy", "'''\n Asserts that the passed repos are exactly those defined in the\n config file. This ensures that we leave no repo unisolated.\n\n For each specified repo, sets the config values specified in its\n `YumDnfConfRepo`, and clears `proxy`. Other config keys are left\n unchanged -- but seeing some \"known bad\" configs in the config file\n will cause an assertion error.\n\n IMPORTANT: See the class docblock, this is not **ENOUGH**.\n '''", "# We talk only to a local reposerver.", "# These are not handled for now, but could be supported. The", "# goal of asserting their absence is to avoid accidentally", "# having non-isolated URLs in the config.", "# NB: As with [main], we let the SSL-related options come", "# from the host: `sslcacert`, `sslclientcert`, and `sslclientkey`", "'''\n Set keys that could cause `yum` or `dnf` to interact with the host\n filesystem. IMPORTANT: See the class docblock, this is not ENOUGH.\n '''", "# This list was obtained by scrolling through `man yum.conf`. To be", "# really thorough, we'd also remove glob filesystem dependencies", "# from options like `exclude`, `includepkgs`, `protected_packages`,", "# `exactarchlist`, etc -- but this is a moot point now that all RPM", "# installs go trough a build appliance.", "#", "# `cachedir` and `persistdir` are under `--installroot`, so no", "# isolation needed. However, ensuring defaults makes later", "# container customization (e.g. cleanup) easier. These can be", "# optionalized later if a good reason arises. In that case,", "# remember that `RpmActionItem` has special handling for `cachedir`.", "# default", "# default", "# Specify repos only via this `.conf` -- that eases isolating them.", "# See the note about `cachedir` -- the same logic applies.", "# default", "# Our download path isn't very fast, nor are the CI hosts. So, we make", "# the fetch timeout higher than might be desired on bare-metal hosts.", "# We talk only to a local reposerver.", "# NB: `sslcacert`, `sslclientcert`, and `sslclientkey` are left", "# as-is, though these read from the host filesystem.", "# Allowing arbitrary plugins could easily break isolation, but we", "# are actually only allowing our custom versionlock here.", "# This option seems to only exist for `dnf`.", "# This final block of options seems only to exist for `yum`.", "#", "# Shouldn't make a difference for as-root runs, but it's good hygiene", "# We'll just use `logfile`.", "# Snapshots don't make sense.", "# This option seems dodgy.", "# Make yum fail if one package in a list can't be installed.", "'Outputs a `{yum,dnf}.conf` file with the changed configuration.'" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,622
278
72a203b8dad3878734b206a0596685bde2132d6a
box-key/shanet
csn_searcher/csn/section.py
[ "Apache-2.0" ]
Python
Section
Parameters ---------- body : list This attribute represents the paragraphs, sentences and tokens as one list. It's wraps them in multiple layers: body = [[para_1], ..., [para_L]] para_i = [[sen_1], ..., [sen_M]] sen_j = [word_1, ..., word_N] paper_id : int This indicates which paper a section belongs to. title : str The title of a section. vector : tensor Section vector of output_dim defined in siamese_models module.
Parameters body : list This attribute represents the paragraphs, sentences and tokens as one list.
[ "Parameters", "body", ":", "list", "This", "attribute", "represents", "the", "paragraphs", "sentences", "and", "tokens", "as", "one", "list", "." ]
class Section: """ Parameters ---------- body : list This attribute represents the paragraphs, sentences and tokens as one list. It's wraps them in multiple layers: body = [[para_1], ..., [para_L]] para_i = [[sen_1], ..., [sen_M]] sen_j = [word_1, ..., word_N] paper_id : int This indicates which paper a section belongs to. title : str The title of a section. vector : tensor Section vector of output_dim defined in siamese_models module. """ def __init__(self, article_id, paragraphs, title, citations=None, vector=None): self.article_id = article_id self.vector = vector if len(title) == 0: self.title = EMPTY_SYMBOL else: # self.title = title.lower() self.title = title self.body = self._format_section(paragraphs) self.citations = citations def __repr__(self): return self.title def __len__(self): return len(self.body) def __iter__(self): return iter(self.body) def _format_section(self, paragraphs): # Avoid throwing error during testing try: import spacy except ImportError: raise ImportError('spacy is missing, please run `pip install spacy` and `pip install scispacy`.') try: scispacy = spacy.load('en_core_sci_sm') except OSError: raise OSError('model is not installed, please try the following:\n', '`pip install https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.2.4/en_core_sci_sm-0.2.4.tar.gz`') """ Parameters ---------- paragraphs : list of paragraphs It stores paragraphs as its elements. Returns ------- body : list It stores input section into the following format: body = [[para_1], ..., [para_L]] para_i = [[sen_1], ..., [sen_M]] sen_j = [word_1, ..., word_N] """ body = [] # decompose the body into paragraphs. for para in paragraphs: paragraph = [] # decompose paragraphs into sentences by scispacy # clean texts here with scispacy.disable_pipes("tagger"): _para = scispacy(para) for sentence in _para.sents: # tokenize each sentence by scispacy tokenized_sentence = [token.text for token in sentence] paragraph.append(tokenized_sentence) body.append(paragraph) return body def get_paragraphs(self): """ It returns all paragraphs in section. """ return self.body def num_sentences(self): """ It returns the number of sentences in section. """ count = 0 for para in self.body: count += len(para) return count def get_sentence(self, para_idx): """ It returns a sentence in a paragraph specified by index """ para = self.body[para_idx] return para def num_tokens(self): """ It returns the number of tokens in section. """ count = 0 for para in self.body: for sen in para: count += len(sen) return count def get_tokens(self): """ It returns all the tokens in section. """ tokens = [] for para in self.body: for sen in para: tokens += sen return tokens
[ "class", "Section", ":", "def", "__init__", "(", "self", ",", "article_id", ",", "paragraphs", ",", "title", ",", "citations", "=", "None", ",", "vector", "=", "None", ")", ":", "self", ".", "article_id", "=", "article_id", "self", ".", "vector", "=", "vector", "if", "len", "(", "title", ")", "==", "0", ":", "self", ".", "title", "=", "EMPTY_SYMBOL", "else", ":", "self", ".", "title", "=", "title", "self", ".", "body", "=", "self", ".", "_format_section", "(", "paragraphs", ")", "self", ".", "citations", "=", "citations", "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "title", "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "body", ")", "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "body", ")", "def", "_format_section", "(", "self", ",", "paragraphs", ")", ":", "try", ":", "import", "spacy", "except", "ImportError", ":", "raise", "ImportError", "(", "'spacy is missing, please run `pip install spacy` and `pip install scispacy`.'", ")", "try", ":", "scispacy", "=", "spacy", ".", "load", "(", "'en_core_sci_sm'", ")", "except", "OSError", ":", "raise", "OSError", "(", "'model is not installed, please try the following:\\n'", ",", "'`pip install https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.2.4/en_core_sci_sm-0.2.4.tar.gz`'", ")", "\"\"\"\n Parameters\n ----------\n paragraphs : list of paragraphs\n It stores paragraphs as its elements.\n\n Returns\n -------\n body : list\n It stores input section into the following format:\n body = [[para_1], ..., [para_L]]\n para_i = [[sen_1], ..., [sen_M]]\n sen_j = [word_1, ..., word_N]\n \"\"\"", "body", "=", "[", "]", "for", "para", "in", "paragraphs", ":", "paragraph", "=", "[", "]", "with", "scispacy", ".", "disable_pipes", "(", "\"tagger\"", ")", ":", "_para", "=", "scispacy", "(", "para", ")", "for", "sentence", "in", "_para", ".", "sents", ":", "tokenized_sentence", "=", "[", "token", ".", "text", "for", "token", "in", "sentence", "]", "paragraph", ".", "append", "(", "tokenized_sentence", ")", "body", ".", "append", "(", "paragraph", ")", "return", "body", "def", "get_paragraphs", "(", "self", ")", ":", "\"\"\" It returns all paragraphs in section. \"\"\"", "return", "self", ".", "body", "def", "num_sentences", "(", "self", ")", ":", "\"\"\" It returns the number of sentences in section. \"\"\"", "count", "=", "0", "for", "para", "in", "self", ".", "body", ":", "count", "+=", "len", "(", "para", ")", "return", "count", "def", "get_sentence", "(", "self", ",", "para_idx", ")", ":", "\"\"\" It returns a sentence in a paragraph specified by index \"\"\"", "para", "=", "self", ".", "body", "[", "para_idx", "]", "return", "para", "def", "num_tokens", "(", "self", ")", ":", "\"\"\" It returns the number of tokens in section. \"\"\"", "count", "=", "0", "for", "para", "in", "self", ".", "body", ":", "for", "sen", "in", "para", ":", "count", "+=", "len", "(", "sen", ")", "return", "count", "def", "get_tokens", "(", "self", ")", ":", "\"\"\" It returns all the tokens in section. \"\"\"", "tokens", "=", "[", "]", "for", "para", "in", "self", ".", "body", ":", "for", "sen", "in", "para", ":", "tokens", "+=", "sen", "return", "tokens" ]
Parameters body : list This attribute represents the paragraphs, sentences and tokens as one list.
[ "Parameters", "body", ":", "list", "This", "attribute", "represents", "the", "paragraphs", "sentences", "and", "tokens", "as", "one", "list", "." ]
[ "\"\"\"\n Parameters\n ----------\n body : list\n This attribute represents the paragraphs, sentences and tokens as one\n list. It's wraps them in multiple layers:\n body = [[para_1], ..., [para_L]]\n para_i = [[sen_1], ..., [sen_M]]\n sen_j = [word_1, ..., word_N]\n paper_id : int\n This indicates which paper a section belongs to.\n title : str\n The title of a section.\n vector : tensor\n Section vector of output_dim defined in siamese_models module.\n \"\"\"", "# self.title = title.lower()", "# Avoid throwing error during testing", "\"\"\"\n Parameters\n ----------\n paragraphs : list of paragraphs\n It stores paragraphs as its elements.\n\n Returns\n -------\n body : list\n It stores input section into the following format:\n body = [[para_1], ..., [para_L]]\n para_i = [[sen_1], ..., [sen_M]]\n sen_j = [word_1, ..., word_N]\n \"\"\"", "# decompose the body into paragraphs.", "# decompose paragraphs into sentences by scispacy", "# clean texts here", "# tokenize each sentence by scispacy", "\"\"\" It returns all paragraphs in section. \"\"\"", "\"\"\" It returns the number of sentences in section. \"\"\"", "\"\"\" It returns a sentence in a paragraph specified by index \"\"\"", "\"\"\" It returns the number of tokens in section. \"\"\"", "\"\"\" It returns all the tokens in section. \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
772
123
6ac6762694555aeec3b3b9c741a44da0c2c5cef0
uw-dims/tupelo
http/server/src/main/java/edu/uw/apl/tupelo/http/server/servlet/MiscServlet.java
[ "BSD-3-Clause" ]
Java
MiscServlet
/** * A servlet handling miscellaneous requests (uuid,newSession) concerning the * attached Tupelo store. * * We split the 'http store' into many servlets simply to avoid one big servlet. * * The expected url layout (i.e. path entered into web.xml) for this servlet is * * /uuid * /usablespace * /newsession */
A servlet handling miscellaneous requests (uuid,newSession) concerning the attached Tupelo store. We split the 'http store' into many servlets simply to avoid one big servlet. The expected url layout for this servlet is /uuid /usablespace /newsession
[ "A", "servlet", "handling", "miscellaneous", "requests", "(", "uuid", "newSession", ")", "concerning", "the", "attached", "Tupelo", "store", ".", "We", "split", "the", "'", "http", "store", "'", "into", "many", "servlets", "simply", "to", "avoid", "one", "big", "servlet", ".", "The", "expected", "url", "layout", "for", "this", "servlet", "is", "/", "uuid", "/", "usablespace", "/", "newsession" ]
public class MiscServlet extends HttpServlet { /** * Auto-generated */ private static final long serialVersionUID = -2480560783103716950L; public void init( ServletConfig config ) throws ServletException { super.init( config ); log = LogFactory.getLog( getClass().getPackage().getName() ); /* Locate our Store handler from the context. The bootstrapping ContextListener puts it there */ ServletContext sc = config.getServletContext(); store = (Store)sc.getAttribute( ContextListener.STORE_KEY ); // gson object claimed thread-safe, so can be a member... GsonBuilder gsonb = new GsonBuilder(); gsonb.registerTypeAdapter(Session.class, Constants.SESSIONSERIALIZER ); gson = gsonb.create(); // log.info( getClass() + " " + log ); } /** * We are mapped to /disks/attr/*, so exactly which operation is * being requested is encoded into the PathInfo */ public void doGet( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { String sp = req.getServletPath(); log.debug( "Get.ServletPath: " + sp ); String pi = req.getPathInfo(); log.debug( "Get.PathInfo: " + pi ); if( sp.equals( "/version" ) ) { version( req, res ); return; } if( sp.equals( "/uuid" ) ) { uuid( req, res ); return; } if( sp.equals( "/usablespace" ) ) { usableSpace( req, res ); return; } /* LOOK: Should we allow GETs for content that by definition changes on each request?? */ if( sp.equals( "/newsession" ) ) { newSession( req, res ); return; } } /** * We are mapped to /disks/attr/*, so exactly which operation is * being requested is encoded into the PathInfo */ public void doPost( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { String sp = req.getServletPath(); log.debug( "Post.ServletPath: " + sp ); String pi = req.getPathInfo(); log.debug( "Post.PathInfo: " + pi ); if( sp.equals( "/newsession" ) ) { newSession( req, res ); return; } } private void version( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { ServletContext sc = getServletConfig().getServletContext(); String result = (String)sc.getAttribute( ContextListener.VERSIONKEY ); if( Utils.acceptsJavaObjects( req ) ) { res.setContentType( "application/x-java-serialized-object" ); OutputStream os = res.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( os ); oos.writeObject( result ); } else if( Utils.acceptsJson( req ) ) { res.setContentType( "application/json" ); String json = gson.toJson( result ); PrintWriter pw = res.getWriter(); pw.print( json ); } else { res.setContentType( "text/plain" ); PrintWriter pw = res.getWriter(); pw.println( "" + result ); } } private void uuid( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { UUID result = store.getUUID(); if( Utils.acceptsJavaObjects( req ) ) { res.setContentType( "application/x-java-serialized-object" ); OutputStream os = res.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( os ); oos.writeObject( result ); } else if( Utils.acceptsJson( req ) ) { res.setContentType( "application/json" ); String json = gson.toJson( result ); PrintWriter pw = res.getWriter(); pw.print( json ); } else { res.setContentType( "text/plain" ); PrintWriter pw = res.getWriter(); pw.println( "" + result ); } } private void usableSpace( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { long result = store.getUsableSpace(); if( Utils.acceptsJavaObjects( req ) ) { res.setContentType( "application/x-java-serialized-object" ); OutputStream os = res.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( os ); oos.writeObject( result ); } else if( Utils.acceptsJson( req ) ) { res.setContentType( "application/json" ); String json = gson.toJson( result ); PrintWriter pw = res.getWriter(); pw.print( json ); } else { res.setContentType( "text/plain" ); PrintWriter pw = res.getWriter(); pw.println( "" + result ); } } private void newSession( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { // NOTHING to do with an HttpSession! Session session = store.newSession(); if( Utils.acceptsJavaObjects( req ) ) { res.setContentType( "application/x-java-serialized-object" ); OutputStream os = res.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( os ); oos.writeObject( session ); } else if( Utils.acceptsJson( req ) ) { res.setContentType( "application/json" ); String json = gson.toJson( session ); PrintWriter pw = res.getWriter(); pw.print( json ); } else { res.setContentType( "text/plain" ); PrintWriter pw = res.getWriter(); pw.println( session.format() ); } } private Store store; private Gson gson; private Log log; }
[ "public", "class", "MiscServlet", "extends", "HttpServlet", "{", "/**\n\t * Auto-generated\n\t */", "private", "static", "final", "long", "serialVersionUID", "=", "-", "2480560783103716950L", ";", "public", "void", "init", "(", "ServletConfig", "config", ")", "throws", "ServletException", "{", "super", ".", "init", "(", "config", ")", ";", "log", "=", "LogFactory", ".", "getLog", "(", "getClass", "(", ")", ".", "getPackage", "(", ")", ".", "getName", "(", ")", ")", ";", "/*\n\t\t Locate our Store handler from the context. The\n\t\t bootstrapping ContextListener puts it there\n\t\t*/", "ServletContext", "sc", "=", "config", ".", "getServletContext", "(", ")", ";", "store", "=", "(", "Store", ")", "sc", ".", "getAttribute", "(", "ContextListener", ".", "STORE_KEY", ")", ";", "GsonBuilder", "gsonb", "=", "new", "GsonBuilder", "(", ")", ";", "gsonb", ".", "registerTypeAdapter", "(", "Session", ".", "class", ",", "Constants", ".", "SESSIONSERIALIZER", ")", ";", "gson", "=", "gsonb", ".", "create", "(", ")", ";", "}", "/**\n\t * We are mapped to /disks/attr/*, so exactly which operation is\n\t * being requested is encoded into the PathInfo\n\t */", "public", "void", "doGet", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "ServletException", "{", "String", "sp", "=", "req", ".", "getServletPath", "(", ")", ";", "log", ".", "debug", "(", "\"", "Get.ServletPath: ", "\"", "+", "sp", ")", ";", "String", "pi", "=", "req", ".", "getPathInfo", "(", ")", ";", "log", ".", "debug", "(", "\"", "Get.PathInfo: ", "\"", "+", "pi", ")", ";", "if", "(", "sp", ".", "equals", "(", "\"", "/version", "\"", ")", ")", "{", "version", "(", "req", ",", "res", ")", ";", "return", ";", "}", "if", "(", "sp", ".", "equals", "(", "\"", "/uuid", "\"", ")", ")", "{", "uuid", "(", "req", ",", "res", ")", ";", "return", ";", "}", "if", "(", "sp", ".", "equals", "(", "\"", "/usablespace", "\"", ")", ")", "{", "usableSpace", "(", "req", ",", "res", ")", ";", "return", ";", "}", "/*\n\t\t LOOK: Should we allow GETs for content that by definition\n\t\t changes on each request??\n\t\t*/", "if", "(", "sp", ".", "equals", "(", "\"", "/newsession", "\"", ")", ")", "{", "newSession", "(", "req", ",", "res", ")", ";", "return", ";", "}", "}", "/**\n\t * We are mapped to /disks/attr/*, so exactly which operation is\n\t * being requested is encoded into the PathInfo\n\t */", "public", "void", "doPost", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "ServletException", "{", "String", "sp", "=", "req", ".", "getServletPath", "(", ")", ";", "log", ".", "debug", "(", "\"", "Post.ServletPath: ", "\"", "+", "sp", ")", ";", "String", "pi", "=", "req", ".", "getPathInfo", "(", ")", ";", "log", ".", "debug", "(", "\"", "Post.PathInfo: ", "\"", "+", "pi", ")", ";", "if", "(", "sp", ".", "equals", "(", "\"", "/newsession", "\"", ")", ")", "{", "newSession", "(", "req", ",", "res", ")", ";", "return", ";", "}", "}", "private", "void", "version", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "ServletException", "{", "ServletContext", "sc", "=", "getServletConfig", "(", ")", ".", "getServletContext", "(", ")", ";", "String", "result", "=", "(", "String", ")", "sc", ".", "getAttribute", "(", "ContextListener", ".", "VERSIONKEY", ")", ";", "if", "(", "Utils", ".", "acceptsJavaObjects", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/x-java-serialized-object", "\"", ")", ";", "OutputStream", "os", "=", "res", ".", "getOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "os", ")", ";", "oos", ".", "writeObject", "(", "result", ")", ";", "}", "else", "if", "(", "Utils", ".", "acceptsJson", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/json", "\"", ")", ";", "String", "json", "=", "gson", ".", "toJson", "(", "result", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "print", "(", "json", ")", ";", "}", "else", "{", "res", ".", "setContentType", "(", "\"", "text/plain", "\"", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "println", "(", "\"", "\"", "+", "result", ")", ";", "}", "}", "private", "void", "uuid", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "ServletException", "{", "UUID", "result", "=", "store", ".", "getUUID", "(", ")", ";", "if", "(", "Utils", ".", "acceptsJavaObjects", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/x-java-serialized-object", "\"", ")", ";", "OutputStream", "os", "=", "res", ".", "getOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "os", ")", ";", "oos", ".", "writeObject", "(", "result", ")", ";", "}", "else", "if", "(", "Utils", ".", "acceptsJson", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/json", "\"", ")", ";", "String", "json", "=", "gson", ".", "toJson", "(", "result", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "print", "(", "json", ")", ";", "}", "else", "{", "res", ".", "setContentType", "(", "\"", "text/plain", "\"", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "println", "(", "\"", "\"", "+", "result", ")", ";", "}", "}", "private", "void", "usableSpace", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "ServletException", "{", "long", "result", "=", "store", ".", "getUsableSpace", "(", ")", ";", "if", "(", "Utils", ".", "acceptsJavaObjects", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/x-java-serialized-object", "\"", ")", ";", "OutputStream", "os", "=", "res", ".", "getOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "os", ")", ";", "oos", ".", "writeObject", "(", "result", ")", ";", "}", "else", "if", "(", "Utils", ".", "acceptsJson", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/json", "\"", ")", ";", "String", "json", "=", "gson", ".", "toJson", "(", "result", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "print", "(", "json", ")", ";", "}", "else", "{", "res", ".", "setContentType", "(", "\"", "text/plain", "\"", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "println", "(", "\"", "\"", "+", "result", ")", ";", "}", "}", "private", "void", "newSession", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "ServletException", "{", "Session", "session", "=", "store", ".", "newSession", "(", ")", ";", "if", "(", "Utils", ".", "acceptsJavaObjects", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/x-java-serialized-object", "\"", ")", ";", "OutputStream", "os", "=", "res", ".", "getOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "os", ")", ";", "oos", ".", "writeObject", "(", "session", ")", ";", "}", "else", "if", "(", "Utils", ".", "acceptsJson", "(", "req", ")", ")", "{", "res", ".", "setContentType", "(", "\"", "application/json", "\"", ")", ";", "String", "json", "=", "gson", ".", "toJson", "(", "session", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "print", "(", "json", ")", ";", "}", "else", "{", "res", ".", "setContentType", "(", "\"", "text/plain", "\"", ")", ";", "PrintWriter", "pw", "=", "res", ".", "getWriter", "(", ")", ";", "pw", ".", "println", "(", "session", ".", "format", "(", ")", ")", ";", "}", "}", "private", "Store", "store", ";", "private", "Gson", "gson", ";", "private", "Log", "log", ";", "}" ]
A servlet handling miscellaneous requests (uuid,newSession) concerning the attached Tupelo store.
[ "A", "servlet", "handling", "miscellaneous", "requests", "(", "uuid", "newSession", ")", "concerning", "the", "attached", "Tupelo", "store", "." ]
[ "// gson object claimed thread-safe, so can be a member...", "//\t\tlog.info( getClass() + \" \" + log );", "// NOTHING to do with an HttpSession!" ]
[ { "param": "HttpServlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpServlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
1,237
79
840b72017e6cd47f7aa993ed1042c661461f5d9f
iwhp/DateTimeExtensions
src/DateTimeExtensions/WorkingDays/HolidayNames.Designer.cs
[ "Apache-2.0" ]
C#
HolidayNames
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class HolidayNames { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal HolidayNames() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DateTimeExtensions.WorkingDays.HolidayNames", typeof(HolidayNames).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string AllSaints { get { return ResourceManager.GetString("AllSaints", resourceCulture); } } public static string Ascension { get { return ResourceManager.GetString("Ascension", resourceCulture); } } public static string Assumption { get { return ResourceManager.GetString("Assumption", resourceCulture); } } public static string Carnival { get { return ResourceManager.GetString("Carnival", resourceCulture); } } public static string Christmas { get { return ResourceManager.GetString("Christmas", resourceCulture); } } public static string ChristmasEve { get { return ResourceManager.GetString("ChristmasEve", resourceCulture); } } public static string CorpusChristi { get { return ResourceManager.GetString("CorpusChristi", resourceCulture); } } public static string DayOfTheDead { get { return ResourceManager.GetString("DayOfTheDead", resourceCulture); } } public static string Easter { get { return ResourceManager.GetString("Easter", resourceCulture); } } public static string EasterMonday { get { return ResourceManager.GetString("EasterMonday", resourceCulture); } } public static string EasterSaturday { get { return ResourceManager.GetString("EasterSaturday", resourceCulture); } } public static string Epiphany { get { return ResourceManager.GetString("Epiphany", resourceCulture); } } public static string Espanha_ConstitutionDay { get { return ResourceManager.GetString("Espanha_ConstitutionDay", resourceCulture); } } public static string Espanha_NationalDay { get { return ResourceManager.GetString("Espanha_NationalDay", resourceCulture); } } public static string GermanUnityDay { get { return ResourceManager.GetString("GermanUnityDay", resourceCulture); } } public static string GoodFriday { get { return ResourceManager.GetString("GoodFriday", resourceCulture); } } public static string ImaculateConception { get { return ResourceManager.GetString("ImaculateConception", resourceCulture); } } public static string IndependanceDay { get { return ResourceManager.GetString("IndependanceDay", resourceCulture); } } public static string InternationalWorkerDay { get { return ResourceManager.GetString("InternationalWorkerDay", resourceCulture); } } public static string MaundyThursday { get { return ResourceManager.GetString("MaundyThursday", resourceCulture); } } public static string MayDay { get { return ResourceManager.GetString("MayDay", resourceCulture); } } public static string NewYear { get { return ResourceManager.GetString("NewYear", resourceCulture); } } public static string OurLadyOfAparecida { get { return ResourceManager.GetString("OurLadyOfAparecida", resourceCulture); } } public static string PalmSunday { get { return ResourceManager.GetString("PalmSunday", resourceCulture); } } public static string Pentecost { get { return ResourceManager.GetString("Pentecost", resourceCulture); } } public static string PentecostMonday { get { return ResourceManager.GetString("PentecostMonday", resourceCulture); } } public static string Portugal_FreedomDay { get { return ResourceManager.GetString("Portugal_FreedomDay", resourceCulture); } } public static string Portugal_PortugalDay { get { return ResourceManager.GetString("Portugal_PortugalDay", resourceCulture); } } public static string Portugal_RepublicDay { get { return ResourceManager.GetString("Portugal_RepublicDay", resourceCulture); } } public static string Portugal_RestorationIndependance { get { return ResourceManager.GetString("Portugal_RestorationIndependance", resourceCulture); } } public static string RepublicDay { get { return ResourceManager.GetString("RepublicDay", resourceCulture); } } public static string StStephenDay { get { return ResourceManager.GetString("StStephenDay", resourceCulture); } } public static string TiradentesDay { get { return ResourceManager.GetString("TiradentesDay", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "HolidayNames", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "HolidayNames", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "DateTimeExtensions.WorkingDays.HolidayNames", "\"", ",", "typeof", "(", "HolidayNames", ")", ".", "GetTypeInfo", "(", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "AllSaints", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AllSaints", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Ascension", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Ascension", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Assumption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Assumption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Carnival", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Carnival", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Christmas", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Christmas", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ChristmasEve", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ChristmasEve", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CorpusChristi", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CorpusChristi", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DayOfTheDead", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DayOfTheDead", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Easter", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Easter", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EasterMonday", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EasterMonday", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EasterSaturday", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EasterSaturday", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Epiphany", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Epiphany", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Espanha_ConstitutionDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Espanha_ConstitutionDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Espanha_NationalDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Espanha_NationalDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "GermanUnityDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "GermanUnityDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "GoodFriday", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "GoodFriday", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ImaculateConception", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ImaculateConception", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "IndependanceDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "IndependanceDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InternationalWorkerDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InternationalWorkerDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "MaundyThursday", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MaundyThursday", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "MayDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MayDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NewYear", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NewYear", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "OurLadyOfAparecida", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OurLadyOfAparecida", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PalmSunday", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PalmSunday", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Pentecost", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Pentecost", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PentecostMonday", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PentecostMonday", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Portugal_FreedomDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Portugal_FreedomDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Portugal_PortugalDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Portugal_PortugalDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Portugal_RepublicDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Portugal_RepublicDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Portugal_RestorationIndependance", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Portugal_RestorationIndependance", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RepublicDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RepublicDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "StStephenDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "StStephenDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "TiradentesDay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TiradentesDay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to All Saints.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Feast of the Ascension.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Assumption.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Carnival.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Christmas.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Christmas Eve.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Corpus Christi.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Day of the Dead.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Easter.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Easter Monday.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Easter Saturday.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Epiphany.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Constitution Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to National Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to German Unity Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Good Friday.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Imaculate Conception.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Independance Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to International Workers&apos; day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Maundy Thursday.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to May Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to New Year.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Our Lady of Aparecida.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Palm Sunday.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Pentecost.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Pentecost Monday.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Freedom Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Portugal Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Republic Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Restoration of Independance.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Republic Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to St Stephen&apos;s Day.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Tiradentes Day.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,191
84
fc06fec24d40335dda7aaeb7a6a539fb008bd85b
SepandKashani/sdr
sdr/mod.py
[ "BSD-3-Clause" ]
Python
UpDownConverter
Baseband <> Passband modulator. Note: the oscillator's last phase offset is retained between calls. Therefore it is possible to up/down-convert a stream block-wise. (If not using `post_filter` in `down()`.) Caveat: don't use the same object for up-conversion and down-conversion as oscillator is up/down-agnostic.
Baseband <> Passband modulator. Note: the oscillator's last phase offset is retained between calls. Therefore it is possible to up/down-convert a stream block-wise. (If not using `post_filter` in `down()`.) don't use the same object for up-conversion and down-conversion as oscillator is up/down-agnostic.
[ "Baseband", "<", ">", "Passband", "modulator", ".", "Note", ":", "the", "oscillator", "'", "s", "last", "phase", "offset", "is", "retained", "between", "calls", ".", "Therefore", "it", "is", "possible", "to", "up", "/", "down", "-", "convert", "a", "stream", "block", "-", "wise", ".", "(", "If", "not", "using", "`", "post_filter", "`", "in", "`", "down", "()", "`", ".", ")", "don", "'", "t", "use", "the", "same", "object", "for", "up", "-", "conversion", "and", "down", "-", "conversion", "as", "oscillator", "is", "up", "/", "down", "-", "agnostic", "." ]
class UpDownConverter: """ Baseband <> Passband modulator. Note: the oscillator's last phase offset is retained between calls. Therefore it is possible to up/down-convert a stream block-wise. (If not using `post_filter` in `down()`.) Caveat: don't use the same object for up-conversion and down-conversion as oscillator is up/down-agnostic. """ def __init__(self, sample_rate: int): assert sample_rate > 0 self._sample_rate = sample_rate self._offset = 1 # \phi def up(self, x: np.ndarray, fc: float, axis: int = -1) -> np.ndarray: r""" Up-convert signal(s) `x` to center frequency `fc`. Parameters ---------- x: np.ndarray[float/complex] (..., N_sample, ...) continous signal(s) to up-convert. Sample rate = `sample_rate` fc: float Target center frequency [Hz]. axis: int Dimension along which to up-convert. (Default: -1) Returns ------- y: np.ndarray[float] (..., N_sample, ...) up-converted continuous signal(s). Sample rate = `sample_rate` y(t) = \sqrt{2} \Re{ x(t) \exp(j 2 \pi f_{c} t + \phi) } """ assert fc > 0 assert -x.ndim <= axis < x.ndim t = np.arange(x.shape[axis] + 1) / self._sample_rate # +1 to compute offset mod = np.exp(1j * (2 * np.pi * fc) * t) * self._offset mod, self._offset = np.sqrt(2) * mod[:-1], mod[-1] sh = [1] * x.ndim sh[axis] = -1 return (y := np.real(x * mod.reshape(sh))) def down(self, x: np.ndarray, fc: float, post_filter: np.ndarray, axis: int = -1) -> np.ndarray: r""" Down-convert signal(s) `x` from center frequency `fc` to baseband. Parameters ---------- x: np.ndarray[float] (..., N_sample, ...) continuous signal(s) to down-convert. Sample rate = `sample_rate` fc: float Current center frequency [Hz]. post_filter: np.ndarray[float/complex] (N_tap,) low-pass filtering kernel. Sample rate = `sample_rate` axis:int Dimension along which to down-convert. (Default: -1) Returns ------- y: np.ndarray[float/complex] (..., N_sample, ...) down-converted continuous signal(s). Sample rate = `sample_rate` y(t) = { \sqrt{2} x(t) \exp(-j 2 \pi f_{c} t + \phi) } \conv LP """ assert fc > 0 assert post_filter.ndim == 1 assert -x.ndim <= axis < x.ndim t = np.arange(x.shape[axis] + 1) / self._sample_rate # +1 to compute offset mod = np.exp(-1j * (2 * np.pi * fc) * t) * self._offset mod, self._offset = np.sqrt(2) * mod[:-1], mod[-1] sh = [1] * x.ndim sh[axis] = -1 return (y := sps.upfirdn(post_filter, x * mod.reshape(sh), axis=axis))
[ "class", "UpDownConverter", ":", "def", "__init__", "(", "self", ",", "sample_rate", ":", "int", ")", ":", "assert", "sample_rate", ">", "0", "self", ".", "_sample_rate", "=", "sample_rate", "self", ".", "_offset", "=", "1", "def", "up", "(", "self", ",", "x", ":", "np", ".", "ndarray", ",", "fc", ":", "float", ",", "axis", ":", "int", "=", "-", "1", ")", "->", "np", ".", "ndarray", ":", "r\"\"\"\n Up-convert signal(s) `x` to center frequency `fc`.\n\n Parameters\n ----------\n x: np.ndarray[float/complex]\n (..., N_sample, ...) continous signal(s) to up-convert.\n Sample rate = `sample_rate`\n fc: float\n Target center frequency [Hz].\n axis: int\n Dimension along which to up-convert. (Default: -1)\n\n Returns\n -------\n y: np.ndarray[float]\n (..., N_sample, ...) up-converted continuous signal(s).\n Sample rate = `sample_rate`\n\n y(t) = \\sqrt{2} \\Re{ x(t) \\exp(j 2 \\pi f_{c} t + \\phi) }\n \"\"\"", "assert", "fc", ">", "0", "assert", "-", "x", ".", "ndim", "<=", "axis", "<", "x", ".", "ndim", "t", "=", "np", ".", "arange", "(", "x", ".", "shape", "[", "axis", "]", "+", "1", ")", "/", "self", ".", "_sample_rate", "mod", "=", "np", ".", "exp", "(", "1j", "*", "(", "2", "*", "np", ".", "pi", "*", "fc", ")", "*", "t", ")", "*", "self", ".", "_offset", "mod", ",", "self", ".", "_offset", "=", "np", ".", "sqrt", "(", "2", ")", "*", "mod", "[", ":", "-", "1", "]", ",", "mod", "[", "-", "1", "]", "sh", "=", "[", "1", "]", "*", "x", ".", "ndim", "sh", "[", "axis", "]", "=", "-", "1", "return", "(", "y", ":=", "np", ".", "real", "(", "x", "*", "mod", ".", "reshape", "(", "sh", ")", ")", ")", "def", "down", "(", "self", ",", "x", ":", "np", ".", "ndarray", ",", "fc", ":", "float", ",", "post_filter", ":", "np", ".", "ndarray", ",", "axis", ":", "int", "=", "-", "1", ")", "->", "np", ".", "ndarray", ":", "r\"\"\"\n Down-convert signal(s) `x` from center frequency `fc` to baseband.\n\n Parameters\n ----------\n x: np.ndarray[float]\n (..., N_sample, ...) continuous signal(s) to down-convert.\n Sample rate = `sample_rate`\n fc: float\n Current center frequency [Hz].\n post_filter: np.ndarray[float/complex]\n (N_tap,) low-pass filtering kernel.\n Sample rate = `sample_rate`\n axis:int\n Dimension along which to down-convert. (Default: -1)\n\n Returns\n -------\n y: np.ndarray[float/complex]\n (..., N_sample, ...) down-converted continuous signal(s).\n Sample rate = `sample_rate`\n\n y(t) = { \\sqrt{2} x(t) \\exp(-j 2 \\pi f_{c} t + \\phi) } \\conv LP\n \"\"\"", "assert", "fc", ">", "0", "assert", "post_filter", ".", "ndim", "==", "1", "assert", "-", "x", ".", "ndim", "<=", "axis", "<", "x", ".", "ndim", "t", "=", "np", ".", "arange", "(", "x", ".", "shape", "[", "axis", "]", "+", "1", ")", "/", "self", ".", "_sample_rate", "mod", "=", "np", ".", "exp", "(", "-", "1j", "*", "(", "2", "*", "np", ".", "pi", "*", "fc", ")", "*", "t", ")", "*", "self", ".", "_offset", "mod", ",", "self", ".", "_offset", "=", "np", ".", "sqrt", "(", "2", ")", "*", "mod", "[", ":", "-", "1", "]", ",", "mod", "[", "-", "1", "]", "sh", "=", "[", "1", "]", "*", "x", ".", "ndim", "sh", "[", "axis", "]", "=", "-", "1", "return", "(", "y", ":=", "sps", ".", "upfirdn", "(", "post_filter", ",", "x", "*", "mod", ".", "reshape", "(", "sh", ")", ",", "axis", "=", "axis", ")", ")" ]
Baseband <> Passband modulator.
[ "Baseband", "<", ">", "Passband", "modulator", "." ]
[ "\"\"\"\n Baseband <> Passband modulator.\n\n Note: the oscillator's last phase offset is retained between calls. Therefore it is possible to\n up/down-convert a stream block-wise. (If not using `post_filter` in `down()`.)\n\n Caveat: don't use the same object for up-conversion and down-conversion as oscillator is\n up/down-agnostic.\n \"\"\"", "# \\phi", "r\"\"\"\n Up-convert signal(s) `x` to center frequency `fc`.\n\n Parameters\n ----------\n x: np.ndarray[float/complex]\n (..., N_sample, ...) continous signal(s) to up-convert.\n Sample rate = `sample_rate`\n fc: float\n Target center frequency [Hz].\n axis: int\n Dimension along which to up-convert. (Default: -1)\n\n Returns\n -------\n y: np.ndarray[float]\n (..., N_sample, ...) up-converted continuous signal(s).\n Sample rate = `sample_rate`\n\n y(t) = \\sqrt{2} \\Re{ x(t) \\exp(j 2 \\pi f_{c} t + \\phi) }\n \"\"\"", "# +1 to compute offset", "r\"\"\"\n Down-convert signal(s) `x` from center frequency `fc` to baseband.\n\n Parameters\n ----------\n x: np.ndarray[float]\n (..., N_sample, ...) continuous signal(s) to down-convert.\n Sample rate = `sample_rate`\n fc: float\n Current center frequency [Hz].\n post_filter: np.ndarray[float/complex]\n (N_tap,) low-pass filtering kernel.\n Sample rate = `sample_rate`\n axis:int\n Dimension along which to down-convert. (Default: -1)\n\n Returns\n -------\n y: np.ndarray[float/complex]\n (..., N_sample, ...) down-converted continuous signal(s).\n Sample rate = `sample_rate`\n\n y(t) = { \\sqrt{2} x(t) \\exp(-j 2 \\pi f_{c} t + \\phi) } \\conv LP\n \"\"\"", "# +1 to compute offset" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
800
82
47c36f4906344cb7d27d28a50a0547d1a1e534e1
TilStehle/DESMO-JS
src/desmoj/core/report/TraceNote.java
[ "Apache-2.0" ]
Java
TraceNote
/** * Represents a message produced by a simulation run whenever entities and / or * events are scheduled, created, deleted or enqueued. Tracenotes document the * changes of state of the model and allow modellers to trace and check the * model's dynamic behaviour. The basic information needed to trace a model's * changes of state are: * <ul> * <li>The name of the Model this message was produced in</li> * <li>The point of simulation time that this message was created</li> * <li>The name of the event involved in the change of state</li> * <li>The name of the entity or process involved in the change of state</li> * <li>A text to describe the kind of changes made to the model</li> * </ul> * * @version DESMO-J, Ver. 2.5.1e copyright (c) 2017 * @author Tim Lechler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You * may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */
Represents a message produced by a simulation run whenever entities and / or events are scheduled, created, deleted or enqueued. Tracenotes document the changes of state of the model and allow modellers to trace and check the model's dynamic behaviour. The basic information needed to trace a model's changes of state are: The name of the Model this message was produced in The point of simulation time that this message was created The name of the event involved in the change of state The name of the entity or process involved in the change of state A text to describe the kind of changes made to the model @version DESMO-J, Ver. 2.5.1e copyright (c) 2017 @author Tim Lechler Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Represents", "a", "message", "produced", "by", "a", "simulation", "run", "whenever", "entities", "and", "/", "or", "events", "are", "scheduled", "created", "deleted", "or", "enqueued", ".", "Tracenotes", "document", "the", "changes", "of", "state", "of", "the", "model", "and", "allow", "modellers", "to", "trace", "and", "check", "the", "model", "'", "s", "dynamic", "behaviour", ".", "The", "basic", "information", "needed", "to", "trace", "a", "model", "'", "s", "changes", "of", "state", "are", ":", "The", "name", "of", "the", "Model", "this", "message", "was", "produced", "in", "The", "point", "of", "simulation", "time", "that", "this", "message", "was", "created", "The", "name", "of", "the", "event", "involved", "in", "the", "change", "of", "state", "The", "name", "of", "the", "entity", "or", "process", "involved", "in", "the", "change", "of", "state", "A", "text", "to", "describe", "the", "kind", "of", "changes", "made", "to", "the", "model", "@version", "DESMO", "-", "J", "Ver", ".", "2", ".", "5", ".", "1e", "copyright", "(", "c", ")", "2017", "@author", "Tim", "Lechler", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
public class TraceNote extends Message { /** * The current entity/entities that produced this message. */ private String _who; /** * The current Event that produced this message. is especially useful when * using multiple models. */ private String _what; /** * Creates a new tracenote with the given parameters as initial values. If * <code>null</code> references are given, they are displayed as "----" in * the trace output. * * @param origin * Model : The model that produced this tracenote * @param message * java.lang.String : The actual trace message * @param time * TimeInstant : The point in simulation time this tracenote was * produced * @param entityInvolved * Entity : The entity involved in this change of state * @param eventInvolved * Event : The event involved in this change of state */ public TraceNote(Model origin, String message, TimeInstant time, Entity entityInvolved, EventAbstract eventInvolved) { super(origin, message, time); if (entityInvolved == null) _who = "----"; else _who = entityInvolved.getName(); if (eventInvolved == null) _what = "----"; else _what = eventInvolved.getName(); } /** * Creates a new tracenote with the given parameters as initial values. If * <code>null</code> references are given, they are displayed as "----" in * the trace output. * * @param origin * Model : The model that produced this tracenote * @param message * java.lang.String : The actual trace message * @param time * TimeInstant : The point in simulation time this tracenote was * produced * @param entitiesInvolved * List<Entity> : The entities involved in this change of state * @param eventInvolved * Event : The event involved in this change of state */ public TraceNote(Model origin, String message, TimeInstant time, List<Entity> entitiesInvolved, EventAbstract eventInvolved) { super(origin, message, time); if (entitiesInvolved == null || entitiesInvolved.isEmpty()) _who = "----"; else { _who = entitiesInvolved.get(0).getQuotedName(); if (entitiesInvolved.size() > 1) { _who += entitiesInvolved.size() > 2 ? ", " + entitiesInvolved.get(1).getQuotedName() : " and " + entitiesInvolved.get(1).getQuotedName(); if (entitiesInvolved.size() > 2) { _who += " and " + entitiesInvolved.get(2).getQuotedName(); } } } if (eventInvolved == null) _what = "----"; else _what = eventInvolved.getQuotedName(); } /** * Returns the name of the entity this tracenote evolved from. * * @return java.lang.String : The name of the entity that produced this * tracenote */ public String getEntity() { return _who; } /** * Returns the name of the event described in this tracenote from. * * @return java.lang.String : The name of the event that produced this * tracenote */ public String getEvent() { return _what; } }
[ "public", "class", "TraceNote", "extends", "Message", "{", "/**\n\t * The current entity/entities that produced this message.\n\t */", "private", "String", "_who", ";", "/**\n\t * The current Event that produced this message. is especially useful when\n\t * using multiple models.\n\t */", "private", "String", "_what", ";", "/**\n\t * Creates a new tracenote with the given parameters as initial values. If\n\t * <code>null</code> references are given, they are displayed as \"----\" in\n\t * the trace output.\n\t * \n\t * @param origin\n\t * Model : The model that produced this tracenote\n\t * @param message\n\t * java.lang.String : The actual trace message\n\t * @param time\n\t * TimeInstant : The point in simulation time this tracenote was\n\t * produced\n\t * @param entityInvolved\n\t * Entity : The entity involved in this change of state\n\t * @param eventInvolved\n\t * Event : The event involved in this change of state\n\t */", "public", "TraceNote", "(", "Model", "origin", ",", "String", "message", ",", "TimeInstant", "time", ",", "Entity", "entityInvolved", ",", "EventAbstract", "eventInvolved", ")", "{", "super", "(", "origin", ",", "message", ",", "time", ")", ";", "if", "(", "entityInvolved", "==", "null", ")", "_who", "=", "\"", "----", "\"", ";", "else", "_who", "=", "entityInvolved", ".", "getName", "(", ")", ";", "if", "(", "eventInvolved", "==", "null", ")", "_what", "=", "\"", "----", "\"", ";", "else", "_what", "=", "eventInvolved", ".", "getName", "(", ")", ";", "}", "/**\n * Creates a new tracenote with the given parameters as initial values. If\n * <code>null</code> references are given, they are displayed as \"----\" in\n * the trace output.\n * \n * @param origin\n * Model : The model that produced this tracenote\n * @param message\n * java.lang.String : The actual trace message\n * @param time\n * TimeInstant : The point in simulation time this tracenote was\n * produced\n * @param entitiesInvolved\n * List<Entity> : The entities involved in this change of state\n * @param eventInvolved\n * Event : The event involved in this change of state\n */", "public", "TraceNote", "(", "Model", "origin", ",", "String", "message", ",", "TimeInstant", "time", ",", "List", "<", "Entity", ">", "entitiesInvolved", ",", "EventAbstract", "eventInvolved", ")", "{", "super", "(", "origin", ",", "message", ",", "time", ")", ";", "if", "(", "entitiesInvolved", "==", "null", "||", "entitiesInvolved", ".", "isEmpty", "(", ")", ")", "_who", "=", "\"", "----", "\"", ";", "else", "{", "_who", "=", "entitiesInvolved", ".", "get", "(", "0", ")", ".", "getQuotedName", "(", ")", ";", "if", "(", "entitiesInvolved", ".", "size", "(", ")", ">", "1", ")", "{", "_who", "+=", "entitiesInvolved", ".", "size", "(", ")", ">", "2", "?", "\"", ", ", "\"", "+", "entitiesInvolved", ".", "get", "(", "1", ")", ".", "getQuotedName", "(", ")", ":", "\"", " and ", "\"", "+", "entitiesInvolved", ".", "get", "(", "1", ")", ".", "getQuotedName", "(", ")", ";", "if", "(", "entitiesInvolved", ".", "size", "(", ")", ">", "2", ")", "{", "_who", "+=", "\"", " and ", "\"", "+", "entitiesInvolved", ".", "get", "(", "2", ")", ".", "getQuotedName", "(", ")", ";", "}", "}", "}", "if", "(", "eventInvolved", "==", "null", ")", "_what", "=", "\"", "----", "\"", ";", "else", "_what", "=", "eventInvolved", ".", "getQuotedName", "(", ")", ";", "}", "/**\n\t * Returns the name of the entity this tracenote evolved from.\n\t * \n\t * @return java.lang.String : The name of the entity that produced this\n\t * tracenote\n\t */", "public", "String", "getEntity", "(", ")", "{", "return", "_who", ";", "}", "/**\n\t * Returns the name of the event described in this tracenote from.\n\t * \n\t * @return java.lang.String : The name of the event that produced this\n\t * tracenote\n\t */", "public", "String", "getEvent", "(", ")", "{", "return", "_what", ";", "}", "}" ]
Represents a message produced by a simulation run whenever entities and / or events are scheduled, created, deleted or enqueued.
[ "Represents", "a", "message", "produced", "by", "a", "simulation", "run", "whenever", "entities", "and", "/", "or", "events", "are", "scheduled", "created", "deleted", "or", "enqueued", "." ]
[]
[ { "param": "Message", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Message", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
808
326
f246d067169204f5bb8522881c52679d225a11db
zbrad/VsEmacs
Commands/Text/LineIndentCommand.cs
[ "MIT" ]
C#
LineIndentCommand
/// <summary> /// Recompute the indentation for the current line, delete the indentation on the line, and re-indent it. /// When this command terminates, the caret is between the same two characters it was between when the command started. /// However, if it was in the indentation, then the caret moves to be after the newly inserted indentation. /// The indentation inserted is language context dependent (smart). /// If there's a multi line selection, then no-op. /// /// Keys: Tab /// </summary>
Recompute the indentation for the current line, delete the indentation on the line, and re-indent it. When this command terminates, the caret is between the same two characters it was between when the command started. However, if it was in the indentation, then the caret moves to be after the newly inserted indentation. The indentation inserted is language context dependent (smart). If there's a multi line selection, then no-op. Tab
[ "Recompute", "the", "indentation", "for", "the", "current", "line", "delete", "the", "indentation", "on", "the", "line", "and", "re", "-", "indent", "it", ".", "When", "this", "command", "terminates", "the", "caret", "is", "between", "the", "same", "two", "characters", "it", "was", "between", "when", "the", "command", "started", ".", "However", "if", "it", "was", "in", "the", "indentation", "then", "the", "caret", "moves", "to", "be", "after", "the", "newly", "inserted", "indentation", ".", "The", "indentation", "inserted", "is", "language", "context", "dependent", "(", "smart", ")", ".", "If", "there", "'", "s", "a", "multi", "line", "selection", "then", "no", "-", "op", ".", "Tab" ]
[EmacsCommand(VSConstants.VSStd2KCmdID.TAB, UndoName = "Indent")] internal class LineIndentCommand : EmacsCommand { internal override void Execute(EmacsCommandContext context) { ITextSelection selection = context.TextView.Selection; bool trackCaret = true; bool markSessionActive = context.MarkSession.IsActive; if (context.TextBuffer.IsReadOnly(selection.Start.Position.GetContainingLine().Extent)) { return; } if (!selection.IsEmpty) { if (selection.Mode == TextSelectionMode.Box) { return; } else { VirtualSnapshotSpan selectionSpan = selection.StreamSelectionSpan; if (selectionSpan.Start.Position.GetContainingLine().LineNumber != selectionSpan.End.Position.GetContainingLine().LineNumber) { return; } selection.Clear(); trackCaret = false; } } this.StripWhiteSpace(context.TextView.GetCaretPosition().GetContainingLine()); int? indentation = context.Manager.SmartIndentationService.GetDesiredIndentation(context.TextView, context.TextView.GetCaretPosition().GetContainingLine()); if (indentation.HasValue) { context.TextBuffer.Insert(context.TextView.GetCaretPosition().GetContainingLine().Start, new string(' ', indentation.Value)); if (!context.TextView.Options.IsConvertTabsToSpacesEnabled()) { context.EditorOperations.ConvertSpacesToTabs(); } } else { int caretOffsetFromStart = 0; if (trackCaret) { CaretPosition positionBeforeChange = context.TextView.Caret.Position; context.EditorOperations.MoveToStartOfLineAfterWhiteSpace(false); caretOffsetFromStart = positionBeforeChange.BufferPosition.Position - context.TextView.GetCaretPosition(); } context.EditorOperations.SelectAndMoveCaret( new VirtualSnapshotPoint(context.TextView.GetCaretPosition().GetContainingLine().Start, 0), new VirtualSnapshotPoint(context.TextView.GetCaretPosition().GetContainingLine().End, 0)); context.CommandRouter.ExecuteDTECommand("Edit.FormatSelection"); context.EditorOperations.MoveToStartOfLineAfterWhiteSpace(false); if (caretOffsetFromStart > 0) { context.EditorOperations.MoveCaret(context.TextView.Caret.Position.BufferPosition + caretOffsetFromStart, false); } } if (!markSessionActive) { context.MarkSession.Deactivate(); } } private void StripWhiteSpace(ITextSnapshotLine line) { ITextSnapshot snapshot = line.Snapshot; ITextBuffer buffer = snapshot.TextBuffer; int forwardIterator; int backwardIterator; forwardIterator = line.Start.Position; while (forwardIterator < line.End.Position && IsSpaceCharacter(snapshot[forwardIterator])) { ++forwardIterator; } backwardIterator = line.End.Position - 1; while (backwardIterator > forwardIterator && IsSpaceCharacter(snapshot[backwardIterator])) { --backwardIterator; } if ((backwardIterator != line.End.Position - 1) || (forwardIterator != line.Start.Position)) { using (ITextEdit edit = buffer.CreateEdit()) { edit.Delete(Span.FromBounds(backwardIterator + 1, line.End.Position)); edit.Delete(Span.FromBounds(line.Start.Position, forwardIterator)); edit.Apply(); } } } private static bool IsSpaceCharacter(char c) { return c == '\t' || (int)c == 0x200B || char.GetUnicodeCategory(c) == UnicodeCategory.SpaceSeparator; } }
[ "[", "EmacsCommand", "(", "VSConstants", ".", "VSStd2KCmdID", ".", "TAB", ",", "UndoName", "=", "\"", "Indent", "\"", ")", "]", "internal", "class", "LineIndentCommand", ":", "EmacsCommand", "{", "internal", "override", "void", "Execute", "(", "EmacsCommandContext", "context", ")", "{", "ITextSelection", "selection", "=", "context", ".", "TextView", ".", "Selection", ";", "bool", "trackCaret", "=", "true", ";", "bool", "markSessionActive", "=", "context", ".", "MarkSession", ".", "IsActive", ";", "if", "(", "context", ".", "TextBuffer", ".", "IsReadOnly", "(", "selection", ".", "Start", ".", "Position", ".", "GetContainingLine", "(", ")", ".", "Extent", ")", ")", "{", "return", ";", "}", "if", "(", "!", "selection", ".", "IsEmpty", ")", "{", "if", "(", "selection", ".", "Mode", "==", "TextSelectionMode", ".", "Box", ")", "{", "return", ";", "}", "else", "{", "VirtualSnapshotSpan", "selectionSpan", "=", "selection", ".", "StreamSelectionSpan", ";", "if", "(", "selectionSpan", ".", "Start", ".", "Position", ".", "GetContainingLine", "(", ")", ".", "LineNumber", "!=", "selectionSpan", ".", "End", ".", "Position", ".", "GetContainingLine", "(", ")", ".", "LineNumber", ")", "{", "return", ";", "}", "selection", ".", "Clear", "(", ")", ";", "trackCaret", "=", "false", ";", "}", "}", "this", ".", "StripWhiteSpace", "(", "context", ".", "TextView", ".", "GetCaretPosition", "(", ")", ".", "GetContainingLine", "(", ")", ")", ";", "int", "?", "indentation", "=", "context", ".", "Manager", ".", "SmartIndentationService", ".", "GetDesiredIndentation", "(", "context", ".", "TextView", ",", "context", ".", "TextView", ".", "GetCaretPosition", "(", ")", ".", "GetContainingLine", "(", ")", ")", ";", "if", "(", "indentation", ".", "HasValue", ")", "{", "context", ".", "TextBuffer", ".", "Insert", "(", "context", ".", "TextView", ".", "GetCaretPosition", "(", ")", ".", "GetContainingLine", "(", ")", ".", "Start", ",", "new", "string", "(", "'", " ", "'", ",", "indentation", ".", "Value", ")", ")", ";", "if", "(", "!", "context", ".", "TextView", ".", "Options", ".", "IsConvertTabsToSpacesEnabled", "(", ")", ")", "{", "context", ".", "EditorOperations", ".", "ConvertSpacesToTabs", "(", ")", ";", "}", "}", "else", "{", "int", "caretOffsetFromStart", "=", "0", ";", "if", "(", "trackCaret", ")", "{", "CaretPosition", "positionBeforeChange", "=", "context", ".", "TextView", ".", "Caret", ".", "Position", ";", "context", ".", "EditorOperations", ".", "MoveToStartOfLineAfterWhiteSpace", "(", "false", ")", ";", "caretOffsetFromStart", "=", "positionBeforeChange", ".", "BufferPosition", ".", "Position", "-", "context", ".", "TextView", ".", "GetCaretPosition", "(", ")", ";", "}", "context", ".", "EditorOperations", ".", "SelectAndMoveCaret", "(", "new", "VirtualSnapshotPoint", "(", "context", ".", "TextView", ".", "GetCaretPosition", "(", ")", ".", "GetContainingLine", "(", ")", ".", "Start", ",", "0", ")", ",", "new", "VirtualSnapshotPoint", "(", "context", ".", "TextView", ".", "GetCaretPosition", "(", ")", ".", "GetContainingLine", "(", ")", ".", "End", ",", "0", ")", ")", ";", "context", ".", "CommandRouter", ".", "ExecuteDTECommand", "(", "\"", "Edit.FormatSelection", "\"", ")", ";", "context", ".", "EditorOperations", ".", "MoveToStartOfLineAfterWhiteSpace", "(", "false", ")", ";", "if", "(", "caretOffsetFromStart", ">", "0", ")", "{", "context", ".", "EditorOperations", ".", "MoveCaret", "(", "context", ".", "TextView", ".", "Caret", ".", "Position", ".", "BufferPosition", "+", "caretOffsetFromStart", ",", "false", ")", ";", "}", "}", "if", "(", "!", "markSessionActive", ")", "{", "context", ".", "MarkSession", ".", "Deactivate", "(", ")", ";", "}", "}", "private", "void", "StripWhiteSpace", "(", "ITextSnapshotLine", "line", ")", "{", "ITextSnapshot", "snapshot", "=", "line", ".", "Snapshot", ";", "ITextBuffer", "buffer", "=", "snapshot", ".", "TextBuffer", ";", "int", "forwardIterator", ";", "int", "backwardIterator", ";", "forwardIterator", "=", "line", ".", "Start", ".", "Position", ";", "while", "(", "forwardIterator", "<", "line", ".", "End", ".", "Position", "&&", "IsSpaceCharacter", "(", "snapshot", "[", "forwardIterator", "]", ")", ")", "{", "++", "forwardIterator", ";", "}", "backwardIterator", "=", "line", ".", "End", ".", "Position", "-", "1", ";", "while", "(", "backwardIterator", ">", "forwardIterator", "&&", "IsSpaceCharacter", "(", "snapshot", "[", "backwardIterator", "]", ")", ")", "{", "--", "backwardIterator", ";", "}", "if", "(", "(", "backwardIterator", "!=", "line", ".", "End", ".", "Position", "-", "1", ")", "||", "(", "forwardIterator", "!=", "line", ".", "Start", ".", "Position", ")", ")", "{", "using", "(", "ITextEdit", "edit", "=", "buffer", ".", "CreateEdit", "(", ")", ")", "{", "edit", ".", "Delete", "(", "Span", ".", "FromBounds", "(", "backwardIterator", "+", "1", ",", "line", ".", "End", ".", "Position", ")", ")", ";", "edit", ".", "Delete", "(", "Span", ".", "FromBounds", "(", "line", ".", "Start", ".", "Position", ",", "forwardIterator", ")", ")", ";", "edit", ".", "Apply", "(", ")", ";", "}", "}", "}", "private", "static", "bool", "IsSpaceCharacter", "(", "char", "c", ")", "{", "return", "c", "==", "'", "\\t", "'", "||", "(", "int", ")", "c", "==", "0x200B", "||", "char", ".", "GetUnicodeCategory", "(", "c", ")", "==", "UnicodeCategory", ".", "SpaceSeparator", ";", "}", "}" ]
Recompute the indentation for the current line, delete the indentation on the line, and re-indent it.
[ "Recompute", "the", "indentation", "for", "the", "current", "line", "delete", "the", "indentation", "on", "the", "line", "and", "re", "-", "indent", "it", "." ]
[ "// Return immediately if the buffer is read-only.", "// If there's not a multi-line selection, then clear it and setup for line indentation", "// Since there was a selection on the line before the format, we are not obligated to place the caret at a specific place", "// after the format operation is done", "// Strip any existing whitespace to setup the line for formatting", "// Insert the desired indentation level", "// Finally, are any tab/spaces conversions necessary?", "// We couldn't find any indentation level for the line, try executing the format command as the last resort", "// Remember caret position", "// Format", "// Move to beginning of newly indented line after format operation is done", "// Restore the position of the caret", "// Ensure we restore the state of the mark session after the formatting operation (changing selection activates", "// the mark session automatically and we change the selection during our formatting operation).", "/// <summary>", "/// Removes white space from both ends of a line.", "/// </summary>", "// Detect spaces at the beginning", "// Detect spaces at the end", "/// <summary>", "/// Copied from EditorOperations. Custom definition for Orcas parity.", "/// </summary>" ]
[ { "param": "EmacsCommand", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EmacsCommand", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
753
109
9c59c263ab09d712a2229e19f46277aefab22a37
satrialoka/trieste
trieste/models/config.py
[ "Apache-2.0" ]
Python
ModelConfig
This class is a specification for building a :class:`~trieste.models.TrainableProbabilisticModel`. It is not meant to be used by itself, subclasses that implement the missing asbtract methods should be used instead. These abstract methods define a default optimizer and all models supported by a specific model type (e.g. Gaussian processes implementation). Note that subclasses should also be frozen dataclasses.
This class is a specification for building a
[ "This", "class", "is", "a", "specification", "for", "building", "a" ]
class ModelConfig: """ This class is a specification for building a :class:`~trieste.models.TrainableProbabilisticModel`. It is not meant to be used by itself, subclasses that implement the missing asbtract methods should be used instead. These abstract methods define a default optimizer and all models supported by a specific model type (e.g. Gaussian processes implementation). Note that subclasses should also be frozen dataclasses. """ model: tf.Module | TrainableProbabilisticModel """ The :class:`~trieste.models.TrainableProbabilisticModel`, or the model to wrap in one. """ model_args: dict[str, Any] = field(default_factory=lambda: {}) """ The keyword arguments to pass to the model wrapper. """ optimizer: Any = field(default_factory=lambda: tf.optimizers.Adam()) """ The optimizer with which to train the model (by minimizing its loss function). """ optimizer_args: dict[str, Any] = field(default_factory=lambda: {}) """ The keyword arguments to pass to the optimizer wrapper. """ def __post_init__(self) -> None: self._check_model_type() def supported_models( self, ) -> dict[Any, Callable[[Any, Optimizer], TrainableProbabilisticModel]]: """ Defines all models supported by certain model type (e.g. Gaussian process implementation). This method has to be specified by a model type specific subclass. :return: A mapping of third-party model types to :class:`CustomTrainable` classes that wrap models of those types. """ raise NotImplementedError def _check_model_type(self) -> None: if isinstance(self.model, TrainableProbabilisticModel): return for model_type in self.supported_models(): if isinstance(self.model, model_type): return raise NotImplementedError(f"Not supported type {type(self.model)}") def create_model_interface(self) -> TrainableProbabilisticModel: """ :return: A model built from this model configuration. """ if isinstance(self.model, TrainableProbabilisticModel): return self.model optimizer = create_optimizer(self.optimizer, self.optimizer_args) for model_type, model_interface in self.supported_models().items(): if isinstance(self.model, model_type): return model_interface(self.model, optimizer, **self.model_args) # type: ignore raise NotImplementedError(f"Not supported type {type(self.model)}")
[ "class", "ModelConfig", ":", "model", ":", "tf", ".", "Module", "|", "TrainableProbabilisticModel", "\"\"\" The :class:`~trieste.models.TrainableProbabilisticModel`, or the model to wrap in one. \"\"\"", "model_args", ":", "dict", "[", "str", ",", "Any", "]", "=", "field", "(", "default_factory", "=", "lambda", ":", "{", "}", ")", "\"\"\" The keyword arguments to pass to the model wrapper. \"\"\"", "optimizer", ":", "Any", "=", "field", "(", "default_factory", "=", "lambda", ":", "tf", ".", "optimizers", ".", "Adam", "(", ")", ")", "\"\"\" The optimizer with which to train the model (by minimizing its loss function). \"\"\"", "optimizer_args", ":", "dict", "[", "str", ",", "Any", "]", "=", "field", "(", "default_factory", "=", "lambda", ":", "{", "}", ")", "\"\"\" The keyword arguments to pass to the optimizer wrapper. \"\"\"", "def", "__post_init__", "(", "self", ")", "->", "None", ":", "self", ".", "_check_model_type", "(", ")", "def", "supported_models", "(", "self", ",", ")", "->", "dict", "[", "Any", ",", "Callable", "[", "[", "Any", ",", "Optimizer", "]", ",", "TrainableProbabilisticModel", "]", "]", ":", "\"\"\"\n Defines all models supported by certain model type (e.g. Gaussian process implementation).\n This method has to be specified by a model type specific subclass.\n\n :return: A mapping of third-party model types to :class:`CustomTrainable` classes that wrap\n models of those types.\n \"\"\"", "raise", "NotImplementedError", "def", "_check_model_type", "(", "self", ")", "->", "None", ":", "if", "isinstance", "(", "self", ".", "model", ",", "TrainableProbabilisticModel", ")", ":", "return", "for", "model_type", "in", "self", ".", "supported_models", "(", ")", ":", "if", "isinstance", "(", "self", ".", "model", ",", "model_type", ")", ":", "return", "raise", "NotImplementedError", "(", "f\"Not supported type {type(self.model)}\"", ")", "def", "create_model_interface", "(", "self", ")", "->", "TrainableProbabilisticModel", ":", "\"\"\"\n :return: A model built from this model configuration.\n \"\"\"", "if", "isinstance", "(", "self", ".", "model", ",", "TrainableProbabilisticModel", ")", ":", "return", "self", ".", "model", "optimizer", "=", "create_optimizer", "(", "self", ".", "optimizer", ",", "self", ".", "optimizer_args", ")", "for", "model_type", ",", "model_interface", "in", "self", ".", "supported_models", "(", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "self", ".", "model", ",", "model_type", ")", ":", "return", "model_interface", "(", "self", ".", "model", ",", "optimizer", ",", "**", "self", ".", "model_args", ")", "raise", "NotImplementedError", "(", "f\"Not supported type {type(self.model)}\"", ")" ]
This class is a specification for building a
[ "This", "class", "is", "a", "specification", "for", "building", "a" ]
[ "\"\"\"\n This class is a specification for building a\n :class:`~trieste.models.TrainableProbabilisticModel`. It is not meant to be used by itself,\n subclasses that implement the missing asbtract methods should be used instead. These abstract\n methods define a default optimizer and all models supported by a specific model type (e.g.\n Gaussian processes implementation). Note that subclasses should also be frozen dataclasses.\n \"\"\"", "\"\"\" The :class:`~trieste.models.TrainableProbabilisticModel`, or the model to wrap in one. \"\"\"", "\"\"\" The keyword arguments to pass to the model wrapper. \"\"\"", "\"\"\" The optimizer with which to train the model (by minimizing its loss function). \"\"\"", "\"\"\" The keyword arguments to pass to the optimizer wrapper. \"\"\"", "\"\"\"\n Defines all models supported by certain model type (e.g. Gaussian process implementation).\n This method has to be specified by a model type specific subclass.\n\n :return: A mapping of third-party model types to :class:`CustomTrainable` classes that wrap\n models of those types.\n \"\"\"", "\"\"\"\n :return: A model built from this model configuration.\n \"\"\"", "# type: ignore" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "class", "docstring": "`~trieste.models.TrainableProbabilisticModel`. It is not meant to be used by itself,\nsubclasses that implement the missing asbtract methods should be used instead. These abstract\nmethods define a default optimizer and all models supported by a specific model type . Note that subclasses should also be frozen dataclasses.", "docstring_tokens": [ "`", "~trieste", ".", "models", ".", "TrainableProbabilisticModel", "`", ".", "It", "is", "not", "meant", "to", "be", "used", "by", "itself", "subclasses", "that", "implement", "the", "missing", "asbtract", "methods", "should", "be", "used", "instead", ".", "These", "abstract", "methods", "define", "a", "default", "optimizer", "and", "all", "models", "supported", "by", "a", "specific", "model", "type", ".", "Note", "that", "subclasses", "should", "also", "be", "frozen", "dataclasses", "." ] } ] }
false
14
521
90
f7b9fdde81d9d469aac5eb888cb6afce32205043
transifex/totem
totem/checks/suite.py
[ "MIT" ]
Python
CheckSuite
Executes all checks and stores all results. This is a stateful class that keeps track of how each check went. It is the class that handles all the checks. All it requires is a configuration (what checks to perform and with what parameters) and it handles everything else. In order to use it, you just need to create an instance with all necessary configuration and then call `run()`. All checks run synchronously.
Executes all checks and stores all results. This is a stateful class that keeps track of how each check went. It is the class that handles all the checks. All it requires is a configuration (what checks to perform and with what parameters) and it handles everything else. In order to use it, you just need to create an instance with all necessary configuration and then call `run()`. All checks run synchronously.
[ "Executes", "all", "checks", "and", "stores", "all", "results", ".", "This", "is", "a", "stateful", "class", "that", "keeps", "track", "of", "how", "each", "check", "went", ".", "It", "is", "the", "class", "that", "handles", "all", "the", "checks", ".", "All", "it", "requires", "is", "a", "configuration", "(", "what", "checks", "to", "perform", "and", "with", "what", "parameters", ")", "and", "it", "handles", "everything", "else", ".", "In", "order", "to", "use", "it", "you", "just", "need", "to", "create", "an", "instance", "with", "all", "necessary", "configuration", "and", "then", "call", "`", "run", "()", "`", ".", "All", "checks", "run", "synchronously", "." ]
class CheckSuite: """Executes all checks and stores all results. This is a stateful class that keeps track of how each check went. It is the class that handles all the checks. All it requires is a configuration (what checks to perform and with what parameters) and it handles everything else. In order to use it, you just need to create an instance with all necessary configuration and then call `run()`. All checks run synchronously. """ def __init__( self, config: Config, content_provider_factory: BaseGitContentProviderFactory, check_factory: CheckFactory, checks: List[str] = None, ): """Constructor. :param Config config: an object that contains all configuration options, including the checks to run and the parameters for each :param BaseGitContentProviderFactory content_provider_factory: an object that knows how to create content providers for a specific Git service :param CheckFactory check_factory: an object that knows how to create Check subclasses for every known configuration type :param List[str] checks: a list of IDs of checks to include in this run """ self._content_provider_factory = content_provider_factory self._check_factory = check_factory self.config = config self.included_check_ids = checks or self.config.check_config_types self.results = CheckSuiteResults() def run(self): """Execute all checks that the suite contains and store the results. Checks are executed synchronously, one by one. This is the main point of the application where the actual magic happens. """ for config in self.config.check_configs: check_type = config.check_type if check_type not in self.included_check_ids: print('Ignoring check "{}"'.format(check_type)) continue results = self._run_check(config, self._check_factory) for r in results: self.results.add(r) def _run_check( self, config: CheckConfig, factory: CheckFactory ) -> List[CheckResult]: """Execute a check for the given configuration. :param CheckConfig config: the configuration of the check :param CheckFactory factory: the factory to use to create checks :return: a list of CheckResult objects :rtype: List """ # For every configuration object a proper content provider # is created and then given to a check object that knows # what to test check = factory.create(config) if not check: msg = ( 'Check with type "{}" could not be created. ' 'Make sure that CheckFactory knows how to create it' ).format(config.check_type) return [CheckResult(config, STATUS_ERROR, ERROR_GENERIC, message=msg)] try: content_provider = self._content_provider_factory.create(check) if not content_provider: factory_type = type(self._content_provider_factory) msg = ( 'Content provider could not be created for check "{}". ' 'Make sure that {}.{} knows how to create it' ).format( check.check_type, factory_type.__module__, factory_type.__name__ ) return [CheckResult(config, STATUS_ERROR, ERROR_GENERIC, message=msg)] content = content_provider.get_content() return check.run(content) except Exception as e: return [CheckResult(config, STATUS_ERROR, ERROR_GENERIC, message=str(e))]
[ "class", "CheckSuite", ":", "def", "__init__", "(", "self", ",", "config", ":", "Config", ",", "content_provider_factory", ":", "BaseGitContentProviderFactory", ",", "check_factory", ":", "CheckFactory", ",", "checks", ":", "List", "[", "str", "]", "=", "None", ",", ")", ":", "\"\"\"Constructor.\n\n :param Config config: an object that contains all configuration options,\n including the checks to run and the parameters for each\n :param BaseGitContentProviderFactory content_provider_factory: an object that\n knows how to create content providers for a specific Git service\n :param CheckFactory check_factory: an object that knows how to create\n Check subclasses for every known configuration type\n :param List[str] checks: a list of IDs of checks to include in this run\n \"\"\"", "self", ".", "_content_provider_factory", "=", "content_provider_factory", "self", ".", "_check_factory", "=", "check_factory", "self", ".", "config", "=", "config", "self", ".", "included_check_ids", "=", "checks", "or", "self", ".", "config", ".", "check_config_types", "self", ".", "results", "=", "CheckSuiteResults", "(", ")", "def", "run", "(", "self", ")", ":", "\"\"\"Execute all checks that the suite contains and store the results.\n\n Checks are executed synchronously, one by one.\n This is the main point of the application where the actual magic happens.\n \"\"\"", "for", "config", "in", "self", ".", "config", ".", "check_configs", ":", "check_type", "=", "config", ".", "check_type", "if", "check_type", "not", "in", "self", ".", "included_check_ids", ":", "print", "(", "'Ignoring check \"{}\"'", ".", "format", "(", "check_type", ")", ")", "continue", "results", "=", "self", ".", "_run_check", "(", "config", ",", "self", ".", "_check_factory", ")", "for", "r", "in", "results", ":", "self", ".", "results", ".", "add", "(", "r", ")", "def", "_run_check", "(", "self", ",", "config", ":", "CheckConfig", ",", "factory", ":", "CheckFactory", ")", "->", "List", "[", "CheckResult", "]", ":", "\"\"\"Execute a check for the given configuration.\n\n :param CheckConfig config: the configuration of the check\n :param CheckFactory factory: the factory to use to create checks\n :return: a list of CheckResult objects\n :rtype: List\n \"\"\"", "check", "=", "factory", ".", "create", "(", "config", ")", "if", "not", "check", ":", "msg", "=", "(", "'Check with type \"{}\" could not be created. '", "'Make sure that CheckFactory knows how to create it'", ")", ".", "format", "(", "config", ".", "check_type", ")", "return", "[", "CheckResult", "(", "config", ",", "STATUS_ERROR", ",", "ERROR_GENERIC", ",", "message", "=", "msg", ")", "]", "try", ":", "content_provider", "=", "self", ".", "_content_provider_factory", ".", "create", "(", "check", ")", "if", "not", "content_provider", ":", "factory_type", "=", "type", "(", "self", ".", "_content_provider_factory", ")", "msg", "=", "(", "'Content provider could not be created for check \"{}\". '", "'Make sure that {}.{} knows how to create it'", ")", ".", "format", "(", "check", ".", "check_type", ",", "factory_type", ".", "__module__", ",", "factory_type", ".", "__name__", ")", "return", "[", "CheckResult", "(", "config", ",", "STATUS_ERROR", ",", "ERROR_GENERIC", ",", "message", "=", "msg", ")", "]", "content", "=", "content_provider", ".", "get_content", "(", ")", "return", "check", ".", "run", "(", "content", ")", "except", "Exception", "as", "e", ":", "return", "[", "CheckResult", "(", "config", ",", "STATUS_ERROR", ",", "ERROR_GENERIC", ",", "message", "=", "str", "(", "e", ")", ")", "]" ]
Executes all checks and stores all results.
[ "Executes", "all", "checks", "and", "stores", "all", "results", "." ]
[ "\"\"\"Executes all checks and stores all results.\n\n This is a stateful class that keeps track of how each check went.\n It is the class that handles all the checks. All it requires is\n a configuration (what checks to perform and with what parameters)\n and it handles everything else.\n\n In order to use it, you just need to create an instance with\n all necessary configuration and then call `run()`.\n All checks run synchronously.\n \"\"\"", "\"\"\"Constructor.\n\n :param Config config: an object that contains all configuration options,\n including the checks to run and the parameters for each\n :param BaseGitContentProviderFactory content_provider_factory: an object that\n knows how to create content providers for a specific Git service\n :param CheckFactory check_factory: an object that knows how to create\n Check subclasses for every known configuration type\n :param List[str] checks: a list of IDs of checks to include in this run\n \"\"\"", "\"\"\"Execute all checks that the suite contains and store the results.\n\n Checks are executed synchronously, one by one.\n This is the main point of the application where the actual magic happens.\n \"\"\"", "\"\"\"Execute a check for the given configuration.\n\n :param CheckConfig config: the configuration of the check\n :param CheckFactory factory: the factory to use to create checks\n :return: a list of CheckResult objects\n :rtype: List\n \"\"\"", "# For every configuration object a proper content provider", "# is created and then given to a check object that knows", "# what to test" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
733
96
d9b00210300f19c56c298af7988486d7da38c72d
hexthedev/HexCS-Networking
Runtime/TCPIPModel/TransportLayer/UDP/UdpSocket.cs
[ "MIT" ]
C#
UdpSocket
/// <summary> /// Represents a connection to a UdpServer. Since UdpServers do not actually /// create a connection, this class can be thought of as a UdpClient auto receiver /// and sender when the UdpClient is supposed to send and receive to a single server. /// /// In the case where the UdpClient needs to send and receive to and from multiple users /// this clas isn't useful. This connection discards all packets received from an conneciton /// other than the specified remote host, and can only send packets to the remote host in question /// </summary>
Represents a connection to a UdpServer. Since UdpServers do not actually create a connection, this class can be thought of as a UdpClient auto receiver and sender when the UdpClient is supposed to send and receive to a single server. In the case where the UdpClient needs to send and receive to and from multiple users this clas isn't useful. This connection discards all packets received from an conneciton other than the specified remote host, and can only send packets to the remote host in question
[ "Represents", "a", "connection", "to", "a", "UdpServer", ".", "Since", "UdpServers", "do", "not", "actually", "create", "a", "connection", "this", "class", "can", "be", "thought", "of", "as", "a", "UdpClient", "auto", "receiver", "and", "sender", "when", "the", "UdpClient", "is", "supposed", "to", "send", "and", "receive", "to", "a", "single", "server", ".", "In", "the", "case", "where", "the", "UdpClient", "needs", "to", "send", "and", "receive", "to", "and", "from", "multiple", "users", "this", "clas", "isn", "'", "t", "useful", ".", "This", "connection", "discards", "all", "packets", "received", "from", "an", "conneciton", "other", "than", "the", "specified", "remote", "host", "and", "can", "only", "send", "packets", "to", "the", "remote", "host", "in", "question" ]
public class UdpSocket: ADisposableManager { private const int cMillisPerCheck = 10; private RecurrentAsyncAction _receiver; private ConcurrentQueue<UdpReceiveResult> _sendQueue = new ConcurrentQueue<UdpReceiveResult>(); private RecurrentAsyncAction _sender; private List<IPEndPoint> _connections = new List<IPEndPoint>(); #region Protected API protected override string AccessAfterDisposalMessage => $"Disposed Error: Cannot access {nameof(UdpSocket)} after disposal"; protected override void SetDisposablesToNull() { Client = null; _sender = null; _receiver = null; } #endregion #region Public API public UdpClient Client { get; private set; } public event Action<UdpReceiveResult> OnReceiveAsync; public UdpSocket(IPEndPoint localEndpoint) { Client = new UdpClient(localEndpoint); RegisterInteralDisposable(Client); _sender = new RecurrentAsyncAction(HandleSend); RegisterInteralDisposable(_sender); _receiver = new RecurrentAsyncAction(HandleReceive); RegisterInteralDisposable(_receiver); } public void Send(byte[] data, IPEndPoint remote) => _sendQueue.Enqueue(new UdpReceiveResult(data, remote)); public void SendToAll(byte[] data) { foreach(IPEndPoint con in _connections) { Send(data, con); } } public bool IsConnection(IPEndPoint endpoint) => _connections.QueryContains(i => i.Address.Equals(endpoint.Address) && i.Port == endpoint.Port); public void RegisterConnection(IPEndPoint endpoint) { if (!IsConnection(endpoint)) { _connections.Add(endpoint); } } #endregion private async Task HandleSend() { while(_sendQueue.Count > 0 && _sendQueue.TryDequeue(out UdpReceiveResult res)) { await Client.SendAsync(res.Buffer, res.Buffer.Length, res.RemoteEndPoint); } await Task.Delay(cMillisPerCheck); } private async Task HandleReceive() { while (Client.Available > 0) { UdpReceiveResult res = await Client.ReceiveAsync(); if (res != default(UdpReceiveResult)) { OnReceiveAsync?.Invoke(res); } } await Task.Delay(cMillisPerCheck); } }
[ "public", "class", "UdpSocket", ":", "ADisposableManager", "{", "private", "const", "int", "cMillisPerCheck", "=", "10", ";", "private", "RecurrentAsyncAction", "_receiver", ";", "private", "ConcurrentQueue", "<", "UdpReceiveResult", ">", "_sendQueue", "=", "new", "ConcurrentQueue", "<", "UdpReceiveResult", ">", "(", ")", ";", "private", "RecurrentAsyncAction", "_sender", ";", "private", "List", "<", "IPEndPoint", ">", "_connections", "=", "new", "List", "<", "IPEndPoint", ">", "(", ")", ";", "region", " Protected API", "protected", "override", "string", "AccessAfterDisposalMessage", "=>", "$\"", "Disposed Error: Cannot access ", "{", "nameof", "(", "UdpSocket", ")", "}", " after disposal", "\"", ";", "protected", "override", "void", "SetDisposablesToNull", "(", ")", "{", "Client", "=", "null", ";", "_sender", "=", "null", ";", "_receiver", "=", "null", ";", "}", "endregion", "region", " Public API", "public", "UdpClient", "Client", "{", "get", ";", "private", "set", ";", "}", "public", "event", "Action", "<", "UdpReceiveResult", ">", "OnReceiveAsync", ";", "public", "UdpSocket", "(", "IPEndPoint", "localEndpoint", ")", "{", "Client", "=", "new", "UdpClient", "(", "localEndpoint", ")", ";", "RegisterInteralDisposable", "(", "Client", ")", ";", "_sender", "=", "new", "RecurrentAsyncAction", "(", "HandleSend", ")", ";", "RegisterInteralDisposable", "(", "_sender", ")", ";", "_receiver", "=", "new", "RecurrentAsyncAction", "(", "HandleReceive", ")", ";", "RegisterInteralDisposable", "(", "_receiver", ")", ";", "}", "public", "void", "Send", "(", "byte", "[", "]", "data", ",", "IPEndPoint", "remote", ")", "=>", "_sendQueue", ".", "Enqueue", "(", "new", "UdpReceiveResult", "(", "data", ",", "remote", ")", ")", ";", "public", "void", "SendToAll", "(", "byte", "[", "]", "data", ")", "{", "foreach", "(", "IPEndPoint", "con", "in", "_connections", ")", "{", "Send", "(", "data", ",", "con", ")", ";", "}", "}", "public", "bool", "IsConnection", "(", "IPEndPoint", "endpoint", ")", "=>", "_connections", ".", "QueryContains", "(", "i", "=>", "i", ".", "Address", ".", "Equals", "(", "endpoint", ".", "Address", ")", "&&", "i", ".", "Port", "==", "endpoint", ".", "Port", ")", ";", "public", "void", "RegisterConnection", "(", "IPEndPoint", "endpoint", ")", "{", "if", "(", "!", "IsConnection", "(", "endpoint", ")", ")", "{", "_connections", ".", "Add", "(", "endpoint", ")", ";", "}", "}", "endregion", "private", "async", "Task", "HandleSend", "(", ")", "{", "while", "(", "_sendQueue", ".", "Count", ">", "0", "&&", "_sendQueue", ".", "TryDequeue", "(", "out", "UdpReceiveResult", "res", ")", ")", "{", "await", "Client", ".", "SendAsync", "(", "res", ".", "Buffer", ",", "res", ".", "Buffer", ".", "Length", ",", "res", ".", "RemoteEndPoint", ")", ";", "}", "await", "Task", ".", "Delay", "(", "cMillisPerCheck", ")", ";", "}", "private", "async", "Task", "HandleReceive", "(", ")", "{", "while", "(", "Client", ".", "Available", ">", "0", ")", "{", "UdpReceiveResult", "res", "=", "await", "Client", ".", "ReceiveAsync", "(", ")", ";", "if", "(", "res", "!=", "default", "(", "UdpReceiveResult", ")", ")", "{", "OnReceiveAsync", "?", ".", "Invoke", "(", "res", ")", ";", "}", "}", "await", "Task", ".", "Delay", "(", "cMillisPerCheck", ")", ";", "}", "}" ]
Represents a connection to a UdpServer.
[ "Represents", "a", "connection", "to", "a", "UdpServer", "." ]
[ "// millis per check", "/// <inheritdoc />", "/// <inheritdoc />", "/// <summary>", "/// The client used by the connection to send and receive data", "/// </summary>", "/// <summary>", "/// Invoked whenever a packet is received. This may be called from another thread", "/// and is guarenteed to be called async", "/// </summary>", "/// <summary>", "/// Constructor", "/// </summary>", "/// <summary>", "/// Attempts a send to an IPEndpoint", "/// </summary>", "/// <param name=\"data\"></param>", "/// <param name=\"remote\"></param>", "/// <summary>", "/// Send to all connections", "/// </summary>", "/// <param name=\"data\"></param>", "/// <summary>", "/// Determines whether the IpEndpoint is already a connection", "/// </summary>", "/// <param name=\"endpoint\"></param>", "/// <returns></returns>", "/// <summary>", "/// Register an endpoint as a connection", "/// </summary>", "/// <param name=\"endpoint\"></param>" ]
[ { "param": "ADisposableManager", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ADisposableManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
506
127
45220c9bf072da2b22d2c2c5873ca2a126957511
929496959/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_microsoft_com_office_drawing_2017_model3d.g.cs
[ "MIT" ]
C#
Model3DRaster
/// <summary> /// <para>Defines the Model3DRaster Class.</para> /// <para>This class is available in Office 2019 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is am3d:raster.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Blip" /> <c>&lt;am3d:blip></c></description></item> /// </list> /// </remark>
Defines the Model3DRaster Class.This class is available in Office 2019 and above.When the object is serialized out as xml, it's qualified name is am3d:raster.
[ "Defines", "the", "Model3DRaster", "Class", ".", "This", "class", "is", "available", "in", "Office", "2019", "and", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "it", "'", "s", "qualified", "name", "is", "am3d", ":", "raster", "." ]
[SchemaAttr("am3d:raster")] public partial class Model3DRaster : OpenXmlCompositeElement { public Model3DRaster() : base() { } public Model3DRaster(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } public Model3DRaster(params OpenXmlElement[] childElements) : base(childElements) { } public Model3DRaster(string outerXml) : base(outerXml) { } [SchemaAttr("rName")] public StringValue? RName { get => GetAttribute<StringValue>(); set => SetAttribute(value); } [SchemaAttr("rVer")] public StringValue? RVer { get => GetAttribute<StringValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("am3d:raster"); builder.Availability = FileFormatVersions.Office2019; builder.AddChild<DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Blip>(); builder.AddElement<Model3DRaster>() .AddAttribute("rName", a => a.RName, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); }) .AddAttribute("rVer", a => a.RVer, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); }); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Blip), 0, 1, version: FileFormatVersions.Office2019) }; } public DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Blip? Blip { get => GetElement<DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Blip>(); set => SetElement(value); } public override OpenXmlElement CloneNode(bool deep) => CloneImp<Model3DRaster>(deep); }
[ "[", "SchemaAttr", "(", "\"", "am3d:raster", "\"", ")", "]", "public", "partial", "class", "Model3DRaster", ":", "OpenXmlCompositeElement", "{", "public", "Model3DRaster", "(", ")", ":", "base", "(", ")", "{", "}", "public", "Model3DRaster", "(", "IEnumerable", "<", "OpenXmlElement", ">", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "Model3DRaster", "(", "params", "OpenXmlElement", "[", "]", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "Model3DRaster", "(", "string", "outerXml", ")", ":", "base", "(", "outerXml", ")", "{", "}", "[", "SchemaAttr", "(", "\"", "rName", "\"", ")", "]", "public", "StringValue", "?", "RName", "{", "get", "=>", "GetAttribute", "<", "StringValue", ">", "(", ")", ";", "set", "=>", "SetAttribute", "(", "value", ")", ";", "}", "[", "SchemaAttr", "(", "\"", "rVer", "\"", ")", "]", "public", "StringValue", "?", "RVer", "{", "get", "=>", "GetAttribute", "<", "StringValue", ">", "(", ")", ";", "set", "=>", "SetAttribute", "(", "value", ")", ";", "}", "internal", "override", "void", "ConfigureMetadata", "(", "ElementMetadata", ".", "Builder", "builder", ")", "{", "base", ".", "ConfigureMetadata", "(", "builder", ")", ";", "builder", ".", "SetSchema", "(", "\"", "am3d:raster", "\"", ")", ";", "builder", ".", "Availability", "=", "FileFormatVersions", ".", "Office2019", ";", "builder", ".", "AddChild", "<", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Drawing", ".", "Model3D", ".", "Blip", ">", "(", ")", ";", "builder", ".", "AddElement", "<", "Model3DRaster", ">", "(", ")", ".", "AddAttribute", "(", "\"", "rName", "\"", ",", "a", "=>", "a", ".", "RName", ",", "aBuilder", "=>", "{", "aBuilder", ".", "AddValidator", "(", "RequiredValidator", ".", "Instance", ")", ";", "}", ")", ".", "AddAttribute", "(", "\"", "rVer", "\"", ",", "a", "=>", "a", ".", "RVer", ",", "aBuilder", "=>", "{", "aBuilder", ".", "AddValidator", "(", "RequiredValidator", ".", "Instance", ")", ";", "}", ")", ";", "builder", ".", "Particle", "=", "new", "CompositeParticle", ".", "Builder", "(", "ParticleType", ".", "Sequence", ",", "1", ",", "1", ")", "{", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Drawing", ".", "Model3D", ".", "Blip", ")", ",", "0", ",", "1", ",", "version", ":", "FileFormatVersions", ".", "Office2019", ")", "}", ";", "}", "public", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Drawing", ".", "Model3D", ".", "Blip", "?", "Blip", "{", "get", "=>", "GetElement", "<", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Drawing", ".", "Model3D", ".", "Blip", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "public", "override", "OpenXmlElement", "CloneNode", "(", "bool", "deep", ")", "=>", "CloneImp", "<", "Model3DRaster", ">", "(", "deep", ")", ";", "}" ]
Defines the Model3DRaster Class.This class is available in Office 2019 and above.When the object is serialized out as xml, it's qualified name is am3d:raster.
[ "Defines", "the", "Model3DRaster", "Class", ".", "This", "class", "is", "available", "in", "Office", "2019", "and", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "it", "'", "s", "qualified", "name", "is", "am3d", ":", "raster", "." ]
[ "/// <summary>", "/// Initializes a new instance of the Model3DRaster class.", "/// </summary>", "/// <summary>", "/// Initializes a new instance of the Model3DRaster class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the Model3DRaster class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the Model3DRaster class from outer XML.", "/// </summary>", "/// <param name=\"outerXml\">Specifies the outer XML of the element.</param>", "/// <summary>", "/// <para>rName, this property is only available in Office 2019 and later.</para>", "/// <para>Represents the following attribute in the schema: rName</para>", "/// </summary>", "/// <summary>", "/// <para>rVer, this property is only available in Office 2019 and later.</para>", "/// <para>Represents the following attribute in the schema: rVer</para>", "/// </summary>", "/// <summary>", "/// <para>Blip.</para>", "/// <para>Represents the following element tag in the schema: am3d:blip.</para>", "/// </summary>", "/// <remark>", "/// xmlns:am3d = http://schemas.microsoft.com/office/drawing/2017/model3d", "/// </remark>", "/// <inheritdoc/>" ]
[ { "param": "OpenXmlCompositeElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "OpenXmlCompositeElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remark", "docstring": "The following table lists the possible child types:\n", "docstring_tokens": [ "The", "following", "table", "lists", "the", "possible", "child", "types", ":" ] } ] }
false
18
449
145
1a7bd57279ab74a717f0518e92b0dd4166d972b6
vinayakpokharkar/aws-sdk-java
aws-java-sdk-kendra/src/main/java/com/amazonaws/services/kendra/model/ExperienceConfiguration.java
[ "Apache-2.0" ]
Java
ExperienceConfiguration
/** * <p> * Specifies the configuration information for your Amazon Kendra experience. This includes the data source IDs and/or * FAQ IDs, and user or group information to grant access to your Amazon Kendra experience. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kendra-2019-02-03/ExperienceConfiguration" target="_top">AWS API * Documentation</a> */
Specifies the configuration information for your Amazon Kendra experience. This includes the data source IDs and/or FAQ IDs, and user or group information to grant access to your Amazon Kendra experience. @see AWS API Documentation
[ "Specifies", "the", "configuration", "information", "for", "your", "Amazon", "Kendra", "experience", ".", "This", "includes", "the", "data", "source", "IDs", "and", "/", "or", "FAQ", "IDs", "and", "user", "or", "group", "information", "to", "grant", "access", "to", "your", "Amazon", "Kendra", "experience", ".", "@see", "AWS", "API", "Documentation" ]
@Generated("com.amazonaws:aws-java-sdk-code-generator") public class ExperienceConfiguration implements Serializable, Cloneable, StructuredPojo { /** * <p> * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience. * </p> */ private ContentSourceConfiguration contentSourceConfiguration; /** * <p> * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. * </p> */ private UserIdentityConfiguration userIdentityConfiguration; /** * <p> * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience. * </p> * * @param contentSourceConfiguration * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed * via the <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon * Kendra experience. */ public void setContentSourceConfiguration(ContentSourceConfiguration contentSourceConfiguration) { this.contentSourceConfiguration = contentSourceConfiguration; } /** * <p> * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience. * </p> * * @return The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed * via the <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon * Kendra experience. */ public ContentSourceConfiguration getContentSourceConfiguration() { return this.contentSourceConfiguration; } /** * <p> * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience. * </p> * * @param contentSourceConfiguration * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed * via the <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon * Kendra experience. * @return Returns a reference to this object so that method calls can be chained together. */ public ExperienceConfiguration withContentSourceConfiguration(ContentSourceConfiguration contentSourceConfiguration) { setContentSourceConfiguration(contentSourceConfiguration); return this; } /** * <p> * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. * </p> * * @param userIdentityConfiguration * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. */ public void setUserIdentityConfiguration(UserIdentityConfiguration userIdentityConfiguration) { this.userIdentityConfiguration = userIdentityConfiguration; } /** * <p> * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. * </p> * * @return The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. */ public UserIdentityConfiguration getUserIdentityConfiguration() { return this.userIdentityConfiguration; } /** * <p> * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. * </p> * * @param userIdentityConfiguration * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails. * @return Returns a reference to this object so that method calls can be chained together. */ public ExperienceConfiguration withUserIdentityConfiguration(UserIdentityConfiguration userIdentityConfiguration) { setUserIdentityConfiguration(userIdentityConfiguration); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getContentSourceConfiguration() != null) sb.append("ContentSourceConfiguration: ").append(getContentSourceConfiguration()).append(","); if (getUserIdentityConfiguration() != null) sb.append("UserIdentityConfiguration: ").append(getUserIdentityConfiguration()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ExperienceConfiguration == false) return false; ExperienceConfiguration other = (ExperienceConfiguration) obj; if (other.getContentSourceConfiguration() == null ^ this.getContentSourceConfiguration() == null) return false; if (other.getContentSourceConfiguration() != null && other.getContentSourceConfiguration().equals(this.getContentSourceConfiguration()) == false) return false; if (other.getUserIdentityConfiguration() == null ^ this.getUserIdentityConfiguration() == null) return false; if (other.getUserIdentityConfiguration() != null && other.getUserIdentityConfiguration().equals(this.getUserIdentityConfiguration()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getContentSourceConfiguration() == null) ? 0 : getContentSourceConfiguration().hashCode()); hashCode = prime * hashCode + ((getUserIdentityConfiguration() == null) ? 0 : getUserIdentityConfiguration().hashCode()); return hashCode; } @Override public ExperienceConfiguration clone() { try { return (ExperienceConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kendra.model.transform.ExperienceConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
[ "@", "Generated", "(", "\"", "com.amazonaws:aws-java-sdk-code-generator", "\"", ")", "public", "class", "ExperienceConfiguration", "implements", "Serializable", ",", "Cloneable", ",", "StructuredPojo", "{", "/**\n * <p>\n * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the\n * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience.\n * </p>\n */", "private", "ContentSourceConfiguration", "contentSourceConfiguration", ";", "/**\n * <p>\n * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n * </p>\n */", "private", "UserIdentityConfiguration", "userIdentityConfiguration", ";", "/**\n * <p>\n * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the\n * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience.\n * </p>\n * \n * @param contentSourceConfiguration\n * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed\n * via the <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon\n * Kendra experience.\n */", "public", "void", "setContentSourceConfiguration", "(", "ContentSourceConfiguration", "contentSourceConfiguration", ")", "{", "this", ".", "contentSourceConfiguration", "=", "contentSourceConfiguration", ";", "}", "/**\n * <p>\n * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the\n * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience.\n * </p>\n * \n * @return The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed\n * via the <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon\n * Kendra experience.\n */", "public", "ContentSourceConfiguration", "getContentSourceConfiguration", "(", ")", "{", "return", "this", ".", "contentSourceConfiguration", ";", "}", "/**\n * <p>\n * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed via the\n * <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon Kendra experience.\n * </p>\n * \n * @param contentSourceConfiguration\n * The identifiers of your data sources and FAQs. Or, you can specify that you want to use documents indexed\n * via the <code>BatchPutDocument</code> operation. This is the content you want to use for your Amazon\n * Kendra experience.\n * @return Returns a reference to this object so that method calls can be chained together.\n */", "public", "ExperienceConfiguration", "withContentSourceConfiguration", "(", "ContentSourceConfiguration", "contentSourceConfiguration", ")", "{", "setContentSourceConfiguration", "(", "contentSourceConfiguration", ")", ";", "return", "this", ";", "}", "/**\n * <p>\n * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n * </p>\n * \n * @param userIdentityConfiguration\n * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n */", "public", "void", "setUserIdentityConfiguration", "(", "UserIdentityConfiguration", "userIdentityConfiguration", ")", "{", "this", ".", "userIdentityConfiguration", "=", "userIdentityConfiguration", ";", "}", "/**\n * <p>\n * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n * </p>\n * \n * @return The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n */", "public", "UserIdentityConfiguration", "getUserIdentityConfiguration", "(", ")", "{", "return", "this", ".", "userIdentityConfiguration", ";", "}", "/**\n * <p>\n * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n * </p>\n * \n * @param userIdentityConfiguration\n * The Amazon Web Services SSO field name that contains the identifiers of your users, such as their emails.\n * @return Returns a reference to this object so that method calls can be chained together.\n */", "public", "ExperienceConfiguration", "withUserIdentityConfiguration", "(", "UserIdentityConfiguration", "userIdentityConfiguration", ")", "{", "setUserIdentityConfiguration", "(", "userIdentityConfiguration", ")", ";", "return", "this", ";", "}", "/**\n * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be\n * redacted from this string using a placeholder value.\n *\n * @return A string representation of this object.\n *\n * @see java.lang.Object#toString()\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "{", "\"", ")", ";", "if", "(", "getContentSourceConfiguration", "(", ")", "!=", "null", ")", "sb", ".", "append", "(", "\"", "ContentSourceConfiguration: ", "\"", ")", ".", "append", "(", "getContentSourceConfiguration", "(", ")", ")", ".", "append", "(", "\"", ",", "\"", ")", ";", "if", "(", "getUserIdentityConfiguration", "(", ")", "!=", "null", ")", "sb", ".", "append", "(", "\"", "UserIdentityConfiguration: ", "\"", ")", ".", "append", "(", "getUserIdentityConfiguration", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", "}", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "return", "true", ";", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "obj", "instanceof", "ExperienceConfiguration", "==", "false", ")", "return", "false", ";", "ExperienceConfiguration", "other", "=", "(", "ExperienceConfiguration", ")", "obj", ";", "if", "(", "other", ".", "getContentSourceConfiguration", "(", ")", "==", "null", "^", "this", ".", "getContentSourceConfiguration", "(", ")", "==", "null", ")", "return", "false", ";", "if", "(", "other", ".", "getContentSourceConfiguration", "(", ")", "!=", "null", "&&", "other", ".", "getContentSourceConfiguration", "(", ")", ".", "equals", "(", "this", ".", "getContentSourceConfiguration", "(", ")", ")", "==", "false", ")", "return", "false", ";", "if", "(", "other", ".", "getUserIdentityConfiguration", "(", ")", "==", "null", "^", "this", ".", "getUserIdentityConfiguration", "(", ")", "==", "null", ")", "return", "false", ";", "if", "(", "other", ".", "getUserIdentityConfiguration", "(", ")", "!=", "null", "&&", "other", ".", "getUserIdentityConfiguration", "(", ")", ".", "equals", "(", "this", ".", "getUserIdentityConfiguration", "(", ")", ")", "==", "false", ")", "return", "false", ";", "return", "true", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "hashCode", "=", "1", ";", "hashCode", "=", "prime", "*", "hashCode", "+", "(", "(", "getContentSourceConfiguration", "(", ")", "==", "null", ")", "?", "0", ":", "getContentSourceConfiguration", "(", ")", ".", "hashCode", "(", ")", ")", ";", "hashCode", "=", "prime", "*", "hashCode", "+", "(", "(", "getUserIdentityConfiguration", "(", ")", "==", "null", ")", "?", "0", ":", "getUserIdentityConfiguration", "(", ")", ".", "hashCode", "(", ")", ")", ";", "return", "hashCode", ";", "}", "@", "Override", "public", "ExperienceConfiguration", "clone", "(", ")", "{", "try", "{", "return", "(", "ExperienceConfiguration", ")", "super", ".", "clone", "(", ")", ";", "}", "catch", "(", "CloneNotSupportedException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "Got a CloneNotSupportedException from Object.clone() ", "\"", "+", "\"", "even though we're Cloneable!", "\"", ",", "e", ")", ";", "}", "}", "@", "com", ".", "amazonaws", ".", "annotation", ".", "SdkInternalApi", "@", "Override", "public", "void", "marshall", "(", "ProtocolMarshaller", "protocolMarshaller", ")", "{", "com", ".", "amazonaws", ".", "services", ".", "kendra", ".", "model", ".", "transform", ".", "ExperienceConfigurationMarshaller", ".", "getInstance", "(", ")", ".", "marshall", "(", "this", ",", "protocolMarshaller", ")", ";", "}", "}" ]
<p> Specifies the configuration information for your Amazon Kendra experience.
[ "<p", ">", "Specifies", "the", "configuration", "information", "for", "your", "Amazon", "Kendra", "experience", "." ]
[]
[ { "param": "Serializable, Cloneable, StructuredPojo", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable, Cloneable, StructuredPojo", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,476
97
c7036568e482f054490f2cc2695a291674022d73
chewtoys/wrender
src/origins/identicon.js
[ "MIT" ]
JavaScript
Identicon
/** * * Procedural image generator. * Creates a PNG as a Buffer object from any input string. * Based on Identicon.js but updated to support: * - optional grid size * - renders to Node.js Buffer * - async rendering to prevent CPU blocking with large images * * -- BASED ON --- * Identicon.js 2.3.1 * http://github.com/stewartlord/identicon.js * Copyright 2017, Stewart Lord * Released under the BSD license * http://www.opensource.org/licenses/bsd-license.php * */
Procedural image generator. Creates a PNG as a Buffer object from any input string. Based on Identicon.js but updated to support: - optional grid size - renders to Node.js Buffer - async rendering to prevent CPU blocking with large images
[ "Procedural", "image", "generator", ".", "Creates", "a", "PNG", "as", "a", "Buffer", "object", "from", "any", "input", "string", ".", "Based", "on", "Identicon", ".", "js", "but", "updated", "to", "support", ":", "-", "optional", "grid", "size", "-", "renders", "to", "Node", ".", "js", "Buffer", "-", "async", "rendering", "to", "prevent", "CPU", "blocking", "with", "large", "images" ]
class Identicon { constructor(hash, options) { if (options.gridSize) options.gridSize = parseInt(options.gridSize, 10); if (options.size) options.size = parseInt(options.size, 10); if (options.gridSize && (parseInt(options.gridSize, 10) % 2) === 0) { throw new Error('gridSize must be an odd number'); } this.options = Object.assign({}, DEFAULTS, options || {}); this.hash = crypto.createHash('sha512').update(hash).digest('hex'); this.size = this.options.size; this.gridSize = this.options.gridSize; this.margin = Math.max(Math.round(this.options.margin), 1); const hue = parseInt(this.hash.substr(-7), 16) / 0xfffffff; const { saturation, brightness } = this.options; if (this.options.invert === true) { this.foreground = this.options.background; this.background = hsl2rgb(hue, saturation, brightness); this.foreground2 = hsl2rgb(hue, Math.max(saturation - 0.3, 0), Math.min(brightness + 0.3, 1)); } else { this.background = this.options.background; this.foreground = hsl2rgb(hue, saturation, brightness); this.foreground2 = hsl2rgb(hue, Math.max(saturation - 0.3, 0), Math.min(brightness + 0.3, 1)); } this.image = new PNGlib(this.size, this.size, 256); } // Loops through the pixel grid and determines which colour to draw // Resolves to a PNG Buffer async render() { const gridWithmargin = (this.gridSize + (2 * this.margin)); const widthPx = Math.round(this.size / gridWithmargin); const bg = this.image.color.apply(this.image, this.background); const fg = this.image.color.apply(this.image, this.foreground); const fg2 = this.image.color.apply(this.image, this.foreground2); for (let col = 0; col < gridWithmargin; col++) { for (let row = 0; row < gridWithmargin; row++) { const x = (row * widthPx); const y = (col * widthPx); // Margins if ( col < this.margin || col >= (gridWithmargin - this.margin) || row < this.margin || row >= (gridWithmargin - this.margin) ) { this.rectangle(x, y, widthPx, widthPx, bg); continue; } // Picks a character from the hash let i = (col * gridWithmargin) + row; // If we're 50% across a row, pick backwards if (row > Math.floor(gridWithmargin / 2)) { i = (col * gridWithmargin) + (gridWithmargin - row - 1); } // Loop back to the start if it is too high if (i > this.hash.length) { i -= this.hash.length; } // Set a colour based on the character code let color = bg; if (parseInt(this.hash.charAt(i), 16) % 2) color = fg; else if (parseInt(this.hash.charAt(i), 16) % 3) color = fg2; // Draws a rectangle to the canvas // We make this asynchronous so this nested loop doesn't block the thread await Promise.resolve() .then(() => this.rectangle(x, y, widthPx, widthPx, color)); } } // Asynchronously resolve the PNG as a Buffer object return Promise.resolve(Buffer.from(this.image.getBase64(), 'base64')); } // Write some colour pixels to the PNG rectangle(x, y, w, h, color) { for (let i = x; i < x + w; i++) { for (let j = y; j < y + h; j++) { this.image.buffer[this.image.index(i, j)] = color; } } } }
[ "class", "Identicon", "{", "constructor", "(", "hash", ",", "options", ")", "{", "if", "(", "options", ".", "gridSize", ")", "options", ".", "gridSize", "=", "parseInt", "(", "options", ".", "gridSize", ",", "10", ")", ";", "if", "(", "options", ".", "size", ")", "options", ".", "size", "=", "parseInt", "(", "options", ".", "size", ",", "10", ")", ";", "if", "(", "options", ".", "gridSize", "&&", "(", "parseInt", "(", "options", ".", "gridSize", ",", "10", ")", "%", "2", ")", "===", "0", ")", "{", "throw", "new", "Error", "(", "'gridSize must be an odd number'", ")", ";", "}", "this", ".", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "DEFAULTS", ",", "options", "||", "{", "}", ")", ";", "this", ".", "hash", "=", "crypto", ".", "createHash", "(", "'sha512'", ")", ".", "update", "(", "hash", ")", ".", "digest", "(", "'hex'", ")", ";", "this", ".", "size", "=", "this", ".", "options", ".", "size", ";", "this", ".", "gridSize", "=", "this", ".", "options", ".", "gridSize", ";", "this", ".", "margin", "=", "Math", ".", "max", "(", "Math", ".", "round", "(", "this", ".", "options", ".", "margin", ")", ",", "1", ")", ";", "const", "hue", "=", "parseInt", "(", "this", ".", "hash", ".", "substr", "(", "-", "7", ")", ",", "16", ")", "/", "0xfffffff", ";", "const", "{", "saturation", ",", "brightness", "}", "=", "this", ".", "options", ";", "if", "(", "this", ".", "options", ".", "invert", "===", "true", ")", "{", "this", ".", "foreground", "=", "this", ".", "options", ".", "background", ";", "this", ".", "background", "=", "hsl2rgb", "(", "hue", ",", "saturation", ",", "brightness", ")", ";", "this", ".", "foreground2", "=", "hsl2rgb", "(", "hue", ",", "Math", ".", "max", "(", "saturation", "-", "0.3", ",", "0", ")", ",", "Math", ".", "min", "(", "brightness", "+", "0.3", ",", "1", ")", ")", ";", "}", "else", "{", "this", ".", "background", "=", "this", ".", "options", ".", "background", ";", "this", ".", "foreground", "=", "hsl2rgb", "(", "hue", ",", "saturation", ",", "brightness", ")", ";", "this", ".", "foreground2", "=", "hsl2rgb", "(", "hue", ",", "Math", ".", "max", "(", "saturation", "-", "0.3", ",", "0", ")", ",", "Math", ".", "min", "(", "brightness", "+", "0.3", ",", "1", ")", ")", ";", "}", "this", ".", "image", "=", "new", "PNGlib", "(", "this", ".", "size", ",", "this", ".", "size", ",", "256", ")", ";", "}", "async", "render", "(", ")", "{", "const", "gridWithmargin", "=", "(", "this", ".", "gridSize", "+", "(", "2", "*", "this", ".", "margin", ")", ")", ";", "const", "widthPx", "=", "Math", ".", "round", "(", "this", ".", "size", "/", "gridWithmargin", ")", ";", "const", "bg", "=", "this", ".", "image", ".", "color", ".", "apply", "(", "this", ".", "image", ",", "this", ".", "background", ")", ";", "const", "fg", "=", "this", ".", "image", ".", "color", ".", "apply", "(", "this", ".", "image", ",", "this", ".", "foreground", ")", ";", "const", "fg2", "=", "this", ".", "image", ".", "color", ".", "apply", "(", "this", ".", "image", ",", "this", ".", "foreground2", ")", ";", "for", "(", "let", "col", "=", "0", ";", "col", "<", "gridWithmargin", ";", "col", "++", ")", "{", "for", "(", "let", "row", "=", "0", ";", "row", "<", "gridWithmargin", ";", "row", "++", ")", "{", "const", "x", "=", "(", "row", "*", "widthPx", ")", ";", "const", "y", "=", "(", "col", "*", "widthPx", ")", ";", "if", "(", "col", "<", "this", ".", "margin", "||", "col", ">=", "(", "gridWithmargin", "-", "this", ".", "margin", ")", "||", "row", "<", "this", ".", "margin", "||", "row", ">=", "(", "gridWithmargin", "-", "this", ".", "margin", ")", ")", "{", "this", ".", "rectangle", "(", "x", ",", "y", ",", "widthPx", ",", "widthPx", ",", "bg", ")", ";", "continue", ";", "}", "let", "i", "=", "(", "col", "*", "gridWithmargin", ")", "+", "row", ";", "if", "(", "row", ">", "Math", ".", "floor", "(", "gridWithmargin", "/", "2", ")", ")", "{", "i", "=", "(", "col", "*", "gridWithmargin", ")", "+", "(", "gridWithmargin", "-", "row", "-", "1", ")", ";", "}", "if", "(", "i", ">", "this", ".", "hash", ".", "length", ")", "{", "i", "-=", "this", ".", "hash", ".", "length", ";", "}", "let", "color", "=", "bg", ";", "if", "(", "parseInt", "(", "this", ".", "hash", ".", "charAt", "(", "i", ")", ",", "16", ")", "%", "2", ")", "color", "=", "fg", ";", "else", "if", "(", "parseInt", "(", "this", ".", "hash", ".", "charAt", "(", "i", ")", ",", "16", ")", "%", "3", ")", "color", "=", "fg2", ";", "await", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "this", ".", "rectangle", "(", "x", ",", "y", ",", "widthPx", ",", "widthPx", ",", "color", ")", ")", ";", "}", "}", "return", "Promise", ".", "resolve", "(", "Buffer", ".", "from", "(", "this", ".", "image", ".", "getBase64", "(", ")", ",", "'base64'", ")", ")", ";", "}", "rectangle", "(", "x", ",", "y", ",", "w", ",", "h", ",", "color", ")", "{", "for", "(", "let", "i", "=", "x", ";", "i", "<", "x", "+", "w", ";", "i", "++", ")", "{", "for", "(", "let", "j", "=", "y", ";", "j", "<", "y", "+", "h", ";", "j", "++", ")", "{", "this", ".", "image", ".", "buffer", "[", "this", ".", "image", ".", "index", "(", "i", ",", "j", ")", "]", "=", "color", ";", "}", "}", "}", "}" ]
Procedural image generator.
[ "Procedural", "image", "generator", "." ]
[ "// Loops through the pixel grid and determines which colour to draw", "// Resolves to a PNG Buffer", "// Margins", "// Picks a character from the hash", "// If we're 50% across a row, pick backwards", "// Loop back to the start if it is too high", "// Set a colour based on the character code", "// Draws a rectangle to the canvas", "// We make this asynchronous so this nested loop doesn't block the thread", "// Asynchronously resolve the PNG as a Buffer object", "// Write some colour pixels to the PNG" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
911
125
bd6f92b446cea97ec08a96b4d5e297d094918af5
hybrid1969/RogueSharp
RogueSharp/Algorithms/Graph.cs
[ "MIT" ]
C#
DijkstraShortestPath
/// <summary> /// The DijkstraShortestPath class represents a data type for solving the single-source shortest paths problem /// in edge-weighted digraphs where the edge weights are non-negative /// </summary> /// <seealso href="http://algs4.cs.princeton.edu/44sp/DijkstraSP.java.html">DijkstraSP class from Princeton University's Java Algorithms</seealso>
The DijkstraShortestPath class represents a data type for solving the single-source shortest paths problem in edge-weighted digraphs where the edge weights are non-negative
[ "The", "DijkstraShortestPath", "class", "represents", "a", "data", "type", "for", "solving", "the", "single", "-", "source", "shortest", "paths", "problem", "in", "edge", "-", "weighted", "digraphs", "where", "the", "edge", "weights", "are", "non", "-", "negative" ]
public class DijkstraShortestPath { private readonly double[] _distanceTo; private readonly DirectedEdge[] _edgeTo; private readonly IndexMinPriorityQueue<double> _priorityQueue; public DijkstraShortestPath( EdgeWeightedDigraph graph, int sourceVertex ) { if ( graph == null ) { throw new ArgumentNullException( "graph", "EdgeWeightedDigraph cannot be null" ); } foreach ( DirectedEdge edge in graph.Edges() ) { if ( edge.Weight < 0 ) { throw new ArgumentOutOfRangeException( string.Format( "Edge: '{0}' has negative weight", edge ) ); } } _distanceTo = new double[graph.NumberOfVertices]; _edgeTo = new DirectedEdge[graph.NumberOfVertices]; for ( int v = 0; v < graph.NumberOfVertices; v++ ) { _distanceTo[v] = Double.PositiveInfinity; } _distanceTo[sourceVertex] = 0.0; _priorityQueue = new IndexMinPriorityQueue<double>( graph.NumberOfVertices ); _priorityQueue.Insert( sourceVertex, _distanceTo[sourceVertex] ); while ( !_priorityQueue.IsEmpty() ) { int v = _priorityQueue.DeleteMin(); foreach ( DirectedEdge edge in graph.Adjacent( v ) ) { Relax( edge ); } } } private void Relax( DirectedEdge edge ) { int v = edge.From; int w = edge.To; if ( _distanceTo[w] > _distanceTo[v] + edge.Weight ) { _distanceTo[w] = _distanceTo[v] + edge.Weight; _edgeTo[w] = edge; if ( _priorityQueue.Contains( w ) ) { _priorityQueue.DecreaseKey( w, _distanceTo[w] ); } else { _priorityQueue.Insert( w, _distanceTo[w] ); } } } public double DistanceTo( int destinationVertex ) { return _distanceTo[destinationVertex]; } public bool HasPathTo( int destinationVertex ) { return _distanceTo[destinationVertex] < double.PositiveInfinity; } public IEnumerable<DirectedEdge> PathTo( int destinationVertex ) { if ( !HasPathTo( destinationVertex ) ) { return null; } var path = new Stack<DirectedEdge>(); for ( DirectedEdge edge = _edgeTo[destinationVertex]; edge != null; edge = _edgeTo[edge.From] ) { path.Push( edge ); } return path; } public bool Check( EdgeWeightedDigraph graph, int sourceVertex ) { if ( graph == null ) { throw new ArgumentNullException( "graph", "EdgeWeightedDigraph cannot be null" ); } if ( _distanceTo[sourceVertex] != 0.0 || _edgeTo[sourceVertex] != null ) { return false; } for ( int v = 0; v < graph.NumberOfVertices; v++ ) { if ( v == sourceVertex ) { continue; } if ( _edgeTo[v] == null && _distanceTo[v] != double.PositiveInfinity ) { return false; } } for ( int v = 0; v < graph.NumberOfVertices; v++ ) { foreach ( DirectedEdge edge in graph.Adjacent( v ) ) { int w = edge.To; if ( _distanceTo[v] + edge.Weight < _distanceTo[w] ) { return false; } } } for ( int w = 0; w < graph.NumberOfVertices; w++ ) { if ( _edgeTo[w] == null ) { continue; } DirectedEdge edge = _edgeTo[w]; int v = edge.From; if ( w != edge.To ) { return false; } if ( _distanceTo[v] + edge.Weight != _distanceTo[w] ) { return false; } } return true; } }
[ "public", "class", "DijkstraShortestPath", "{", "private", "readonly", "double", "[", "]", "_distanceTo", ";", "private", "readonly", "DirectedEdge", "[", "]", "_edgeTo", ";", "private", "readonly", "IndexMinPriorityQueue", "<", "double", ">", "_priorityQueue", ";", "public", "DijkstraShortestPath", "(", "EdgeWeightedDigraph", "graph", ",", "int", "sourceVertex", ")", "{", "if", "(", "graph", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "\"", "graph", "\"", ",", "\"", "EdgeWeightedDigraph cannot be null", "\"", ")", ";", "}", "foreach", "(", "DirectedEdge", "edge", "in", "graph", ".", "Edges", "(", ")", ")", "{", "if", "(", "edge", ".", "Weight", "<", "0", ")", "{", "throw", "new", "ArgumentOutOfRangeException", "(", "string", ".", "Format", "(", "\"", "Edge: '{0}' has negative weight", "\"", ",", "edge", ")", ")", ";", "}", "}", "_distanceTo", "=", "new", "double", "[", "graph", ".", "NumberOfVertices", "]", ";", "_edgeTo", "=", "new", "DirectedEdge", "[", "graph", ".", "NumberOfVertices", "]", ";", "for", "(", "int", "v", "=", "0", ";", "v", "<", "graph", ".", "NumberOfVertices", ";", "v", "++", ")", "{", "_distanceTo", "[", "v", "]", "=", "Double", ".", "PositiveInfinity", ";", "}", "_distanceTo", "[", "sourceVertex", "]", "=", "0.0", ";", "_priorityQueue", "=", "new", "IndexMinPriorityQueue", "<", "double", ">", "(", "graph", ".", "NumberOfVertices", ")", ";", "_priorityQueue", ".", "Insert", "(", "sourceVertex", ",", "_distanceTo", "[", "sourceVertex", "]", ")", ";", "while", "(", "!", "_priorityQueue", ".", "IsEmpty", "(", ")", ")", "{", "int", "v", "=", "_priorityQueue", ".", "DeleteMin", "(", ")", ";", "foreach", "(", "DirectedEdge", "edge", "in", "graph", ".", "Adjacent", "(", "v", ")", ")", "{", "Relax", "(", "edge", ")", ";", "}", "}", "}", "private", "void", "Relax", "(", "DirectedEdge", "edge", ")", "{", "int", "v", "=", "edge", ".", "From", ";", "int", "w", "=", "edge", ".", "To", ";", "if", "(", "_distanceTo", "[", "w", "]", ">", "_distanceTo", "[", "v", "]", "+", "edge", ".", "Weight", ")", "{", "_distanceTo", "[", "w", "]", "=", "_distanceTo", "[", "v", "]", "+", "edge", ".", "Weight", ";", "_edgeTo", "[", "w", "]", "=", "edge", ";", "if", "(", "_priorityQueue", ".", "Contains", "(", "w", ")", ")", "{", "_priorityQueue", ".", "DecreaseKey", "(", "w", ",", "_distanceTo", "[", "w", "]", ")", ";", "}", "else", "{", "_priorityQueue", ".", "Insert", "(", "w", ",", "_distanceTo", "[", "w", "]", ")", ";", "}", "}", "}", "public", "double", "DistanceTo", "(", "int", "destinationVertex", ")", "{", "return", "_distanceTo", "[", "destinationVertex", "]", ";", "}", "public", "bool", "HasPathTo", "(", "int", "destinationVertex", ")", "{", "return", "_distanceTo", "[", "destinationVertex", "]", "<", "double", ".", "PositiveInfinity", ";", "}", "public", "IEnumerable", "<", "DirectedEdge", ">", "PathTo", "(", "int", "destinationVertex", ")", "{", "if", "(", "!", "HasPathTo", "(", "destinationVertex", ")", ")", "{", "return", "null", ";", "}", "var", "path", "=", "new", "Stack", "<", "DirectedEdge", ">", "(", ")", ";", "for", "(", "DirectedEdge", "edge", "=", "_edgeTo", "[", "destinationVertex", "]", ";", "edge", "!=", "null", ";", "edge", "=", "_edgeTo", "[", "edge", ".", "From", "]", ")", "{", "path", ".", "Push", "(", "edge", ")", ";", "}", "return", "path", ";", "}", "public", "bool", "Check", "(", "EdgeWeightedDigraph", "graph", ",", "int", "sourceVertex", ")", "{", "if", "(", "graph", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "\"", "graph", "\"", ",", "\"", "EdgeWeightedDigraph cannot be null", "\"", ")", ";", "}", "if", "(", "_distanceTo", "[", "sourceVertex", "]", "!=", "0.0", "||", "_edgeTo", "[", "sourceVertex", "]", "!=", "null", ")", "{", "return", "false", ";", "}", "for", "(", "int", "v", "=", "0", ";", "v", "<", "graph", ".", "NumberOfVertices", ";", "v", "++", ")", "{", "if", "(", "v", "==", "sourceVertex", ")", "{", "continue", ";", "}", "if", "(", "_edgeTo", "[", "v", "]", "==", "null", "&&", "_distanceTo", "[", "v", "]", "!=", "double", ".", "PositiveInfinity", ")", "{", "return", "false", ";", "}", "}", "for", "(", "int", "v", "=", "0", ";", "v", "<", "graph", ".", "NumberOfVertices", ";", "v", "++", ")", "{", "foreach", "(", "DirectedEdge", "edge", "in", "graph", ".", "Adjacent", "(", "v", ")", ")", "{", "int", "w", "=", "edge", ".", "To", ";", "if", "(", "_distanceTo", "[", "v", "]", "+", "edge", ".", "Weight", "<", "_distanceTo", "[", "w", "]", ")", "{", "return", "false", ";", "}", "}", "}", "for", "(", "int", "w", "=", "0", ";", "w", "<", "graph", ".", "NumberOfVertices", ";", "w", "++", ")", "{", "if", "(", "_edgeTo", "[", "w", "]", "==", "null", ")", "{", "continue", ";", "}", "DirectedEdge", "edge", "=", "_edgeTo", "[", "w", "]", ";", "int", "v", "=", "edge", ".", "From", ";", "if", "(", "w", "!=", "edge", ".", "To", ")", "{", "return", "false", ";", "}", "if", "(", "_distanceTo", "[", "v", "]", "+", "edge", ".", "Weight", "!=", "_distanceTo", "[", "w", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "}" ]
The DijkstraShortestPath class represents a data type for solving the single-source shortest paths problem in edge-weighted digraphs where the edge weights are non-negative
[ "The", "DijkstraShortestPath", "class", "represents", "a", "data", "type", "for", "solving", "the", "single", "-", "source", "shortest", "paths", "problem", "in", "edge", "-", "weighted", "digraphs", "where", "the", "edge", "weights", "are", "non", "-", "negative" ]
[ "/// <summary>", "/// Computes a shortest paths tree from the specified sourceVertex to every other vertex in the edge-weighted directed graph", "/// </summary>", "/// <param name=\"graph\">The edge-weighted directed graph</param>", "/// <param name=\"sourceVertex\">The source vertex to compute the shortest paths tree from</param>", "/// <exception cref=\"ArgumentOutOfRangeException\">Throws an ArgumentOutOfRangeException if an edge weight is negative</exception>", "/// <exception cref=\"ArgumentNullException\">Thrown if EdgeWeightedDigraph is null</exception>", "/// <summary>", "/// Returns the length of a shortest path from the sourceVertex to the specified destinationVertex", "/// </summary>", "/// <param name=\"destinationVertex\">The destination vertex to find a shortest path to</param>", "/// <returns>The length of a shortest path from the sourceVertex to the specified destinationVertex or double.PositiveInfinity if no such path exists</returns>", "/// <summary>", "/// Is there a path from the sourceVertex to the specified destinationVertex?", "/// </summary>", "/// <param name=\"destinationVertex\">The destination vertex to see if there is a path to</param>", "/// <returns>True if there is a path from the sourceVertex to the specified destinationVertex, false otherwise</returns>", "/// <summary>", "/// Returns an IEnumerable of DirectedEdges representing a shortest path from the sourceVertex to the specified destinationVertex", "/// </summary>", "/// <param name=\"destinationVertex\">The destination vertex to find a shortest path to</param>", "/// <returns>IEnumerable of DirectedEdges representing a shortest path from the sourceVertex to the specified destinationVertex</returns>", "// TODO: This method should be private and should be called from the bottom of the constructor", "/// <summary>", "/// check optimality conditions:", "/// </summary>", "/// <param name=\"graph\">The edge-weighted directed graph</param>", "/// <param name=\"sourceVertex\">The source vertex to check optimality conditions from</param>", "/// <returns>True if all optimality conditions are met, false otherwise</returns>", "/// <exception cref=\"ArgumentNullException\">Thrown on null EdgeWeightedDigraph</exception>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "seealso", "docstring": "DijkstraSP class from Princeton University's Java Algorithms", "docstring_tokens": [ "DijkstraSP", "class", "from", "Princeton", "University", "'", "s", "Java", "Algorithms" ] } ] }
false
17
897
82
45f396b4a36c5a7477fbcbddefc427e1038cfec4
joek/serverless-talk
deployment/functions/user/node_modules/etcd3/lib/src/lease.js
[ "MIT" ]
JavaScript
Lease
/** * Lease is a high-level manager for etcd leases. * Leases are great for things like service discovery: * * ``` * const os = require('os'); * const { Etcd3 } = require('etcd3'); * const client = new Etcd3(); * * const hostPrefix = 'available-hosts/'; * * function grantLease() { * const lease = client.lease(); * * lease.on('lost', err => { * console.log('We lost our lease as a result of this error:', err); * console.log('Trying to re-grant it...'); * grantLease(); * }) * * await lease.put(hostPrefix + os.hostname()).value(''); * } * * function getAvailableHosts() { * const keys = await client.get().keys().strings(); * return keys.map(key => key.slice(hostPrefix.length)); * } * ``` */
Lease is a high-level manager for etcd leases. Leases are great for things like service discovery. ``` const os = require('os'); const { Etcd3 } = require('etcd3'); const client = new Etcd3(). const hostPrefix = 'available-hosts/'. function grantLease() { const lease = client.lease().
[ "Lease", "is", "a", "high", "-", "level", "manager", "for", "etcd", "leases", ".", "Leases", "are", "great", "for", "things", "like", "service", "discovery", ".", "`", "`", "`", "const", "os", "=", "require", "(", "'", "os", "'", ")", ";", "const", "{", "Etcd3", "}", "=", "require", "(", "'", "etcd3", "'", ")", ";", "const", "client", "=", "new", "Etcd3", "()", ".", "const", "hostPrefix", "=", "'", "available", "-", "hosts", "/", "'", ".", "function", "grantLease", "()", "{", "const", "lease", "=", "client", ".", "lease", "()", "." ]
class Lease extends events_1.EventEmitter { constructor(pool, namespace, ttl, options) { super(); this.pool = pool; this.namespace = namespace; this.ttl = ttl; this.options = options; this.state = 0 /* Alive */; this.client = new RPC.LeaseClient(this.pool); this.teardown = () => { /* noop */ }; if (ttl < 1) { throw new Error(`The TTL in an etcd lease must be at least 1 second. Got: ${ttl}`); } this.leaseID = this.client .leaseGrant({ TTL: ttl }, this.options) .then(res => { this.state = 0 /* Alive */; this.lastKeepAlive = Date.now(); this.keepalive(); return res.ID; }) .catch(err => { this.emit('lost', err); // return, don't throw, from here so that if no one is listening to // grant() we don't crash the process. return err; }); } /** * Grant waits for the lease to be granted. You generally don't need to * call this, as any operations with `.put` will queue automatically. * * Calling this multiple times is safe; it won't try to request multipl leases. * * It rejects if the lease cannot be granted, in additon to the `lost` * event firing. */ grant() { return this.leaseID.then(throwIfError); } /** * Revoke frees the lease from etcd. Keys that the lease owns will be * evicted. */ revoke(options = this.options) { this.close(); return this.leaseID.then(id => { if (!(id instanceof Error)) { // if an error, we didn't grant in the first place return this.client.leaseRevoke({ ID: id }, options).then(() => undefined); } return undefined; }); } /** * Put returns a put builder that operates within the current lease. */ put(key) { return new builder_1.PutBuilder(new RPC.KVClient(new LeaseClientWrapper(this.leaseID, this.pool)), this.namespace, key); } /** * keepaliveOnce fires an immediate keepalive for the lease. */ keepaliveOnce(options = this.options) { return Promise.all([this.client.leaseKeepAlive(options), this.grant()]).then(([stream, id]) => { return new Promise((resolve, reject) => { stream.on('data', resolve); stream.on('error', err => reject(errors_1.castGrpcError(err))); stream.write({ ID: id }); }).then(res => { stream.end(); if (leaseExpired(res)) { const err = new errors_1.EtcdLeaseInvalidError(res.ID); this.emit('lost', err); this.close(); throw err; } return res; }); }); } /** * Returns whether etcd has told us that this lease revoked. */ revoked() { return this.state === 1 /* Revoked */; } /** * Implements EventEmitter.on(...). */ on(event, handler) { // tslint:disable-line return super.on(event, handler); } /** * Tears down resources associated with the lease. */ close() { this.state = 1 /* Revoked */; this.teardown(); } /** * keepalive starts a loop keeping the lease alive. */ keepalive() { // When the cluster goes down, we keep trying to reconnect. But if we're // far past the end of our key's TTL, there's no way we're going to be // able to renew it. Fire a "lost". if (Date.now() - this.lastKeepAlive > 2 * 1000 * this.ttl) { this.emit('lost', new errors_1.GRPCConnectFailedError('We lost connection to etcd and our lease has expired.')); return this.close(); } this.client .leaseKeepAlive() .then(stream => { if (this.state !== 0 /* Alive */) { return stream.end(); } const keepaliveTimer = setInterval(() => this.fireKeepAlive(stream), 1000 * this.ttl / 3); this.teardown = () => { this.teardown = () => undefined; clearInterval(keepaliveTimer); stream.end(); }; stream.on('error', err => this.handleKeepaliveError(err)).on('data', res => { if (leaseExpired(res)) { return this.handleKeepaliveError(new errors_1.EtcdLeaseInvalidError(res.ID)); } this.lastKeepAlive = Date.now(); this.emit('keepaliveSucceeded', res); }); this.emit('keepaliveEstablished'); this.fireKeepAlive(stream); }) .catch(err => this.handleKeepaliveError(err)); } fireKeepAlive(stream) { this.emit('keepaliveFired'); this.grant() .then(id => stream.write({ ID: id })) .catch(() => this.close()); // will only throw if the initial grant failed } handleKeepaliveError(err) { this.emit('keepaliveFailed', errors_1.castGrpcError(err)); this.teardown(); if (err instanceof errors_1.EtcdLeaseInvalidError) { this.emit('lost', err); this.close(); } else { setTimeout(() => this.keepalive(), 100); } } }
[ "class", "Lease", "extends", "events_1", ".", "EventEmitter", "{", "constructor", "(", "pool", ",", "namespace", ",", "ttl", ",", "options", ")", "{", "super", "(", ")", ";", "this", ".", "pool", "=", "pool", ";", "this", ".", "namespace", "=", "namespace", ";", "this", ".", "ttl", "=", "ttl", ";", "this", ".", "options", "=", "options", ";", "this", ".", "state", "=", "0", ";", "this", ".", "client", "=", "new", "RPC", ".", "LeaseClient", "(", "this", ".", "pool", ")", ";", "this", ".", "teardown", "=", "(", ")", "=>", "{", "}", ";", "if", "(", "ttl", "<", "1", ")", "{", "throw", "new", "Error", "(", "`", "${", "ttl", "}", "`", ")", ";", "}", "this", ".", "leaseID", "=", "this", ".", "client", ".", "leaseGrant", "(", "{", "TTL", ":", "ttl", "}", ",", "this", ".", "options", ")", ".", "then", "(", "res", "=>", "{", "this", ".", "state", "=", "0", ";", "this", ".", "lastKeepAlive", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "keepalive", "(", ")", ";", "return", "res", ".", "ID", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "this", ".", "emit", "(", "'lost'", ",", "err", ")", ";", "return", "err", ";", "}", ")", ";", "}", "grant", "(", ")", "{", "return", "this", ".", "leaseID", ".", "then", "(", "throwIfError", ")", ";", "}", "revoke", "(", "options", "=", "this", ".", "options", ")", "{", "this", ".", "close", "(", ")", ";", "return", "this", ".", "leaseID", ".", "then", "(", "id", "=>", "{", "if", "(", "!", "(", "id", "instanceof", "Error", ")", ")", "{", "return", "this", ".", "client", ".", "leaseRevoke", "(", "{", "ID", ":", "id", "}", ",", "options", ")", ".", "then", "(", "(", ")", "=>", "undefined", ")", ";", "}", "return", "undefined", ";", "}", ")", ";", "}", "put", "(", "key", ")", "{", "return", "new", "builder_1", ".", "PutBuilder", "(", "new", "RPC", ".", "KVClient", "(", "new", "LeaseClientWrapper", "(", "this", ".", "leaseID", ",", "this", ".", "pool", ")", ")", ",", "this", ".", "namespace", ",", "key", ")", ";", "}", "keepaliveOnce", "(", "options", "=", "this", ".", "options", ")", "{", "return", "Promise", ".", "all", "(", "[", "this", ".", "client", ".", "leaseKeepAlive", "(", "options", ")", ",", "this", ".", "grant", "(", ")", "]", ")", ".", "then", "(", "(", "[", "stream", ",", "id", "]", ")", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "stream", ".", "on", "(", "'data'", ",", "resolve", ")", ";", "stream", ".", "on", "(", "'error'", ",", "err", "=>", "reject", "(", "errors_1", ".", "castGrpcError", "(", "err", ")", ")", ")", ";", "stream", ".", "write", "(", "{", "ID", ":", "id", "}", ")", ";", "}", ")", ".", "then", "(", "res", "=>", "{", "stream", ".", "end", "(", ")", ";", "if", "(", "leaseExpired", "(", "res", ")", ")", "{", "const", "err", "=", "new", "errors_1", ".", "EtcdLeaseInvalidError", "(", "res", ".", "ID", ")", ";", "this", ".", "emit", "(", "'lost'", ",", "err", ")", ";", "this", ".", "close", "(", ")", ";", "throw", "err", ";", "}", "return", "res", ";", "}", ")", ";", "}", ")", ";", "}", "revoked", "(", ")", "{", "return", "this", ".", "state", "===", "1", ";", "}", "on", "(", "event", ",", "handler", ")", "{", "return", "super", ".", "on", "(", "event", ",", "handler", ")", ";", "}", "close", "(", ")", "{", "this", ".", "state", "=", "1", ";", "this", ".", "teardown", "(", ")", ";", "}", "keepalive", "(", ")", "{", "if", "(", "Date", ".", "now", "(", ")", "-", "this", ".", "lastKeepAlive", ">", "2", "*", "1000", "*", "this", ".", "ttl", ")", "{", "this", ".", "emit", "(", "'lost'", ",", "new", "errors_1", ".", "GRPCConnectFailedError", "(", "'We lost connection to etcd and our lease has expired.'", ")", ")", ";", "return", "this", ".", "close", "(", ")", ";", "}", "this", ".", "client", ".", "leaseKeepAlive", "(", ")", ".", "then", "(", "stream", "=>", "{", "if", "(", "this", ".", "state", "!==", "0", ")", "{", "return", "stream", ".", "end", "(", ")", ";", "}", "const", "keepaliveTimer", "=", "setInterval", "(", "(", ")", "=>", "this", ".", "fireKeepAlive", "(", "stream", ")", ",", "1000", "*", "this", ".", "ttl", "/", "3", ")", ";", "this", ".", "teardown", "=", "(", ")", "=>", "{", "this", ".", "teardown", "=", "(", ")", "=>", "undefined", ";", "clearInterval", "(", "keepaliveTimer", ")", ";", "stream", ".", "end", "(", ")", ";", "}", ";", "stream", ".", "on", "(", "'error'", ",", "err", "=>", "this", ".", "handleKeepaliveError", "(", "err", ")", ")", ".", "on", "(", "'data'", ",", "res", "=>", "{", "if", "(", "leaseExpired", "(", "res", ")", ")", "{", "return", "this", ".", "handleKeepaliveError", "(", "new", "errors_1", ".", "EtcdLeaseInvalidError", "(", "res", ".", "ID", ")", ")", ";", "}", "this", ".", "lastKeepAlive", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "emit", "(", "'keepaliveSucceeded'", ",", "res", ")", ";", "}", ")", ";", "this", ".", "emit", "(", "'keepaliveEstablished'", ")", ";", "this", ".", "fireKeepAlive", "(", "stream", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "this", ".", "handleKeepaliveError", "(", "err", ")", ")", ";", "}", "fireKeepAlive", "(", "stream", ")", "{", "this", ".", "emit", "(", "'keepaliveFired'", ")", ";", "this", ".", "grant", "(", ")", ".", "then", "(", "id", "=>", "stream", ".", "write", "(", "{", "ID", ":", "id", "}", ")", ")", ".", "catch", "(", "(", ")", "=>", "this", ".", "close", "(", ")", ")", ";", "}", "handleKeepaliveError", "(", "err", ")", "{", "this", ".", "emit", "(", "'keepaliveFailed'", ",", "errors_1", ".", "castGrpcError", "(", "err", ")", ")", ";", "this", ".", "teardown", "(", ")", ";", "if", "(", "err", "instanceof", "errors_1", ".", "EtcdLeaseInvalidError", ")", "{", "this", ".", "emit", "(", "'lost'", ",", "err", ")", ";", "this", ".", "close", "(", ")", ";", "}", "else", "{", "setTimeout", "(", "(", ")", "=>", "this", ".", "keepalive", "(", ")", ",", "100", ")", ";", "}", "}", "}" ]
Lease is a high-level manager for etcd leases.
[ "Lease", "is", "a", "high", "-", "level", "manager", "for", "etcd", "leases", "." ]
[ "/* Alive */", "/* noop */", "/* Alive */", "// return, don't throw, from here so that if no one is listening to\r", "// grant() we don't crash the process.\r", "/**\r\n * Grant waits for the lease to be granted. You generally don't need to\r\n * call this, as any operations with `.put` will queue automatically.\r\n *\r\n * Calling this multiple times is safe; it won't try to request multipl leases.\r\n *\r\n * It rejects if the lease cannot be granted, in additon to the `lost`\r\n * event firing.\r\n */", "/**\r\n * Revoke frees the lease from etcd. Keys that the lease owns will be\r\n * evicted.\r\n */", "// if an error, we didn't grant in the first place\r", "/**\r\n * Put returns a put builder that operates within the current lease.\r\n */", "/**\r\n * keepaliveOnce fires an immediate keepalive for the lease.\r\n */", "/**\r\n * Returns whether etcd has told us that this lease revoked.\r\n */", "/* Revoked */", "/**\r\n * Implements EventEmitter.on(...).\r\n */", "// tslint:disable-line\r", "/**\r\n * Tears down resources associated with the lease.\r\n */", "/* Revoked */", "/**\r\n * keepalive starts a loop keeping the lease alive.\r\n */", "// When the cluster goes down, we keep trying to reconnect. But if we're\r", "// far past the end of our key's TTL, there's no way we're going to be\r", "// able to renew it. Fire a \"lost\".\r", "/* Alive */", "// will only throw if the initial grant failed\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
25
1,234
197